Populate specific fields in $lookup

£可爱£侵袭症+ 提交于 2019-12-04 05:07:48

问题


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

 { 
   "$group": {
     "_id": "$userId",
     "projectId": { "$push": "$projectId" }
    }
 },
 { 
  "$lookup": {
     "from": "users",
     "localField": "_id",
     "foreignField": "_id",
      "as": "user"
   }
 },
 {   $unwind:"$user" },
 { 
   "$lookup": {
     "from": "projects",
     "localField": "projectId",
     "foreignField": "_id",
     "as": "projects"
    }
 }

But i want to populate specific fields from that result For this I tried $project, But it combining projectId into one array and projectName into another array.Below is my result json:

[
  {
    "_id": "5c0a29e597e71a0d28b910aa",
    "projectId": [
        "5c0a2a8897e71a0d28b910ac",
        "5c0a4083753a321c6c4ee024"
    ],
    "user": {
        "_id": "5c0a29e597e71a0d28b910aa",
        "firstName": "Amit"
        "lastName": "kumar",
        "type": "developer",
        "status": "active"
    },
    "projects": [
        {
            "_id": "5c0a2a8897e71a0d28b910ac",
            "skypeId": "",
            "projectName": "LN-PM",
            "status": "ongoing",
            "assignId": "5c0a2a0a97e71a0d28b910ab"
        },
        {
            "_id": "5c0a4083753a321c6c4ee024",
            "skypeId": "",
            "status": "pending",
            "assignId": "5c0a2a0a97e71a0d28b910ab"
        }
    ]
  }
]

Now i want to get the only "firstName and _id" field from user field and "projectName and _id" field from the projects field


回答1:


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


来源:https://stackoverflow.com/questions/53680441/populate-specific-fields-in-lookup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!