MongoDB聚合管道查询

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

标签: node.js mongodb aggregation-framework

我正在node.js 8.11.1上使用mongoDB 3.6,并正在使用MongoDB Node.js驱动程序。 我有两个集合,“组”和“用户”:

group:
[  
   {  
      "_id":1,
      "groupName":"group1",
      "users":[  
         {  
            "userId":1,
            "isAdmin":"false"
         },
         {  
            "userId":2,
            "isAdmin":"true"
         }
      ]
   },
   {  
      "_id":2,
      "groupName":"group2",
      "users":[  
         {  
            "userId":2,
            "isAdmin":"false"
         },
         {  
            "userId":3,
            "isAdmin":"true"
         }
      ]
   }
]

user:
[  
   {  
      "_id":1,
      "username":"user1",
      "firstname":"a",
      "lastname":"aa",
      "mobileNo":"+1111111"
   },
   {  
      "_id":2,
      "username":"user2",
      "firstname":"b",
      "lastname":"bb",
      "mobileNo":"+2222222"
   },
   {  
      "_id":3,
      "username":"user3",
      "firstname":"c",
      "lastname":"cc",
      "mobileNo":"+3333333"
   }
]

我需要一个聚合来返回如下内容:

[  
   {  
      "_id":1,
      "groupName":"group1",
      "members":[  
         {  
            "isAdmin":"false",
            "username":"user1",
            "firstname":"a",
            "lastname":"aa"
         },
         {  
            "isAdmin":"true",
            "username":"user2",
            "firstname":"b",
            "lastname":"bb"
         }
      ]
   },
   {  
      "_id":2,
      "groupName":"group2",
      "members":[  
         {  
            "isAdmin":"false",
            "username":"user2",
            "firstname":"b",
            "lastname":"bb"
         },
         {  
            "isAdmin":"true",
            "username":"user3",
            "firstname":"c",
            "lastname":"cc"
         }
      ]
   }
]

结果是在“成员”中,“ isAdmin”从组集合中的“用户”返回,而“用户名”,“名”和“姓”来自用户集合

非常感谢,

Milad。

1 个答案:

答案 0 :(得分:1)

您可以尝试从mongodb 3.6 及更高版本

以下进行聚合
db.group.aggregate([
  { "$unwind": "$users" },
  { "$lookup": {
    "from": Users.collection.name,
    "let": { "userId": "$users.userId", "isAdmin": "$users.isAdmin" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": [ "$_id", "$$userId" ] } } },
      { "$project": { "isAdmin": "$$isAdmin", "username": 1, "firstName": 1, "lastName": 1 }}
    ],
    "as": "members"
  }},
  { "$unwind": "$members" },
  { "$group": {
    "_id": "$_id",
    "members": { "$push": "$members" },
    "groupName": { "$first": "$groupName" }
  }}
])