MongoDB-在主表中的多个列上应用类似的查找

时间:2019-05-01 20:16:23

标签: mongodb mongodb-query aggregation-framework

我是MongoDB的新手,我正在尝试汇总学生的完整详细信息,以供参考其他集合。

students集合结构:

{
    "_id" : ObjectId("5cc973dd008221192148177a"),
    "name" : "James Paulson",
    "teachers" : [ 
        ObjectId("5cc973dd008221192148176f"), 
        ObjectId("5cc973dd0082211921481770")
    ],
    "attenders": [ 
        ObjectId("5cc973dd0082211921481732"), 
        ObjectId("5cc973dd008221192148173f")
    ]
}

staff集合结构:

{
    "_id" : ObjectId("5cc973dd008221192148176f"),
    "name" : "John Paul",
    "subject" : [ 
        "english", 
        "maths"
    ]
}
{
    "_id" : ObjectId("5cc973dd0082211921481771"),
    "name" : "Pattrick",
    "subject" : [ 
        "physics", 
        "history"
    ]
}
{
    "_id" : ObjectId("5cc973dd0082211921481732"),
    "name" : "Roger",
    "subject" : [ 
        "sweeper"
    ]
}
{
    "_id" : ObjectId("5cc973dd008221192148173f"),
    "name" : "Ken",
    "subject" : [ 
        "dentist"
    ]
}

这是我用于检索特定学生的所有老师详细信息的查询。

查询:

db.getCollection('students').aggregate([
  {
    $unwind: "$teachers"
  },      
  {
    $lookup:
    {
        from: 'staff',
        localField: 'teachers',
        foreignField: '_id',
        as: 'teachers'
    }
  }
]);

结果:

{
    "_id" : ObjectId("5cc973dd008221192148177a"),
    "name" : "James Paulson",
    "teachers" : [ 
        {
            "_id" : ObjectId("5cc973dd008221192148176f"),
            "name" : "John Paul",
            "subject" : [ 
                "english", 
                "maths"
            ]
        }, 
        {
            "_id" : ObjectId("5cc973dd008221192148176f"),
            "name" : "Pattrick",
            "subject" : [ 
                "physics", 
                "history"
            ]
        }
    ],
    "attenders": [ 
        ObjectId("5cc973dd0082211921481732"), 
        ObjectId("5cc973dd008221192148173f")
    ]
}

如您所见,attenders数组与teachers相似,除了学生表中列名的不同。那么如何将类似的查询应用于第二列(attenders)?还有什么方法可以从第二个表中选择特定的列(仅像_id集合中的namestaff一样)?

对此将提供任何帮助。

1 个答案:

答案 0 :(得分:1)

您可以在mongodb 3.6 及更高版本

中使用以下聚合

首先,您无需在此处使用$unwind,因为您的字段已经包含ObjectId数组。并且要从引用的集合中选择特定的字段,可以使用带有管道的自定义$lookup和其中的字段$project

db.getCollection('students').aggregate([
  { "$lookup": {
    "from": "staff",
    "let": { "teachers": "$teachers" },
    "pipeline": [
       { "$match": { "$expr": { "$in": [ "$_id", "$$teachers" ] } } }
       { "$project": { "name": 1 }}
     ],
     "as": "teachers"
  }},
  { "$lookup": {
    "from": "attenders",
    "let": { "attenders": "$attenders" },
    "pipeline": [
       { "$match": { "$expr": { "$in": [ "$_id", "$$attenders" ] } } }
     ],
     "as": "attenders"
  }}
])