Populate specific fields in $lookup

前端 未结 1 1347
抹茶落季
抹茶落季 2021-01-22 07:18

I am using aggregate to group and populate the result like below:

 { 
   \"$group\": {
     \"_id\": \"$userId\",
     \"projectId\": { \"$push\": \"$projectId\         


        
相关标签:
1条回答
  • 2021-01-22 07:44

    You can use below aggregation with mongodb 3.6 and above

    With the newer $lookup syntax you can use $projection inside the $lookup pipeline

    db.collection.aggregate([
      { "$group": {
        "_id": "$userId",
        "projectId": { "$push": "$projectId" }
      }},
      { "$lookup": {
        "from": "users",
        "let": { "userId": "$_id" },
        "pipeline": [
          { "$match": { "$expr": { "$eq": [ "$_id", "$$userId" ] }}},
          { "$project": { "firstName": 1 }}
        ],
        "as": "user"
      }},
      { "$unwind": "$user" },
      { "$lookup": {
        "from": "projects",
        "let": { "projectId": "$projectId" },
        "pipeline": [
          { "$match": { "$expr": { "$in": [ "$_id", "$$projectId" ] }}},
          { "$project": { "projectName": 1 }}
        ],
        "as": "projects"
      }}
    ])
    
    0 讨论(0)
提交回复
热议问题