代码之家  ›  专栏  ›  技术社区  ›  Milad Aghamohammadi

MongoDB聚合管道查询

  •  2
  • Milad Aghamohammadi  · 技术社区  · 6 年前

    我有两个集合,“组”和“用户”:

    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”来自用户集合

    非常感谢,

    1 回复  |  直到 6 年前
        1
  •  1
  •   Ashh    6 年前

    您可以在mongodb中尝试以下聚合

    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" }
      }}
    ])