【问题标题】:MongoDB - How to access a newly created array field created with $lookup and aggregate functionMongoDB - 如何访问使用 $lookup 和聚合函数创建的新创建的数组字段
【发布时间】:2022-10-12 22:16:59
【问题描述】:

假设我有两个集合:

培训班:

[
  {
    _id: 1,
    name: "Geometry",
    teacher_id: 1
  },
  {
    _id: 2,
    name: "English",
    teacher_id: 2
  }
]

教师:

[
  {
    _id: 1,
    firstName: "John",
    lastName: "Adams"
  },
  {
     _id: 2,
     firstName: "Mary",
     lastName: "Jane"
  }
]

现在我对两个集合执行聚合以创建类似于 SQL 中的连接的内容:

db.collection("courses").aggregate([
      {
        $lookup:{
              from: "teachers",
              localField: "teacher_id",
              foreignField: "_id",
              as: "teacher_info"
          }
      },
      {
        $match:{
          //I want to perform a match or filter here on the teacher_info
        }
      }
]);

$lookup 和聚合将返回具有新的teacher_info 数组字段的文档列表。

[
  {
    _id: 1,
    name: "Geometry",
    teacher_id: 1,
    teacher_info: [
      {
        _id: 1,
        firstName: "John",
        lastName: "Adams"
      },
   ]
  },
  {
    _id: 2,
    name: "English",
    teacher_id: 1,
    teacher_info: [
      {
         _id: 2,
         firstName: "Mary",
         lastName: "Jane"
      },
   ]
  }
]

我需要在新创建的teacher_info 数组字段中执行匹配操作。例如,只保留名字为“John”的老师。我该怎么做?那可能吗?

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您可以在$match 阶段使用dot notation

    {
      $match: {
        "teacher_info.firstName": "John"
      }
    }
    

    Demo @ Mongo Playground

    【讨论】:

    • 谢谢你,先生。但是,为什么教师的 info.first Name 在引号中?
    • 因为不能允许点符号作为 JSON 属性键不带引号.因此,为避免由此产生的错误,您需要将整个 teacher_info.firstName 括在引号中。
    • 等什么?点不是 json 属性名称
    • 认为这个article 可以帮助你。
    • 谢谢你,先生!
    猜你喜欢
    • 2021-06-10
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多