【问题标题】:MongoDB Aggregate Pipeline queryMongoDB 聚合管道查询
【发布时间】:2018-09-17 08:11:28
【问题描述】:

我在 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"
         }
      ]
   }
]

在结果中的“members”中,“isAdmin”从组集合中的“users”返回,“username”、“firstname”和“lastname”来自用户集合

非常感谢,

米拉德。

【问题讨论】:

    标签: node.js mongodb aggregation-framework


    【解决方案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" }
      }}
    ])
    

    【讨论】:

    • 感谢您的回答,但它会将用户文档的所有字段作为成员字段中的 userId 返回
    猜你喜欢
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 2020-07-27
    • 2019-06-18
    • 2015-04-24
    相关资源
    最近更新 更多