如何在MongoDB中执行联接(在SQL中类似)?

时间:2018-09-18 08:17:11

标签: mongodb join

假设我们有两个collections(用户和数据),需要从用户和数据收集中提取每个user_id的所有数据。

users
     {user_id: 1, username: tom, userage: 27}
     {user_id: 2, username: sam, userage: 25}

data
     {workexp: 4, skill: testing, user_id: 1}
     {workexp: 9, skill: devops, user_id: 2}

请告诉我如何在mongo中执行此操作。

1 个答案:

答案 0 :(得分:0)

您可以使用lookup运算符加入收藏集。

在此处阅读文档: https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

示例:

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}

在您的情况下,如下所示:

db.users.aggregate([
    {
        $lookup: {
           from: "data",
           localField: "user_id",
           foreignField: "user_id",
           as: "user_data"
        }
    }])

这将返回此JSON对象:

{
    "_id" : ObjectId("5ba0bace2fd0cdd3eae35df6"),
    "user_id" : 1,
    "username" : "tom",
    "userage" : 27,
    "user_data" : [ 
        {
            "_id" : ObjectId("5ba0bafe2fd0cdd3eae35e16"),
            "workexp" : 4,
            "skill" : "testing",
            "user_id" : 1
        }
    ]
}