首页 > 解决方案 > MongoDB - 从数组中的所有匹配对象中获取一个字段?

问题描述

我一直在将 mySQL 迁移到 mongoDB。我想嵌入教师,课程表到教师表。我有一个 mongo 数据库结构如下。

{ 
"_id" : "14365", 
"ID" : "14365", 
"name" : "Lembr", 
"dept_name" : "Accounting", 
"salary" : 32241.56, 
"teaches" : [
    {
        "ID" : "14365", 
        "course_id" : "200", 
        "sec_id" : "1", 
        "semester" : "Spring", 
        "year" : 2007.0, 
        "course" : {
            "course_id" : "200", 
            "title" : "The Music of the Ramones", 
            "dept_name" : "Accounting", 
            "credits" : 4.0
        }
    }, 
    {
        "ID" : "14365", 
        "course_id" : "843", 
        "sec_id" : "1", 
        "semester" : "Fall", 
        "year" : 2010.0, 
        "course" : {
            "course_id" : "843", 
            "title" : "Environmental Law", 
            "dept_name" : "Math", 
            "credits" : 4.0
        }
    }
]

}

我想像下面的 SQL 查询一样查询。

SELECT name, title From instructor Natural join teaches Natural join course;

如何在 mongodb 中查询?

标签: databasemongodbmongodb-queryaggregation-framework

解决方案


您需要 MongoDB 的聚合运算符$reduce

db.collection.aggregate([
  /** Using project stage we'll project only needed fields */
  {
    $project: {
      _id: 0, // _id is by default included - you need to exclude it
      name: 1,
      title: {
        $reduce: {
          input: "$teaches", // Iterate on objects of `teaches` array
          initialValue: [], // Initial value
          in: {
            $cond: [
              { $eq: ["$$this.course.dept_name", "$dept_name"] }, // condition to check
              {
                $concatArrays: ["$$value", ["$$this.course.title"]], // If condition is met push values to array
              },
              "$$value" // If not send same holding array back for this iteration
            ]
          }
        }
      }
    }
  }
]);

测试: mongoplayground

测试: $filter : mongoplayground

笔记 :

我们曾经$reduce将数组中不同对象的所有标题teaches带到一个数组中。您也可以使用$filter来实现类似的事情。如果在任何情况下,如果您title只是数组中的一个元素(数组中没有重复元素dept_name) ,teaches那么您可以使用$unwind$arrayElemAttitle数组转换为字符串。


推荐阅读