在$ lookup中填充特定字段

时间:2018-12-08 07:22:16

标签: mongodb mongoose mongodb-query aggregation-framework

我正在使用聚合对结果进行分组和填充,如下所示:

 { 
   "$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"
    }
 }

但是我想从结果中填充特定字段,为此,我尝试了  $ project,但是它将projectId组合到一个数组中,将projectName组合到另一个数组中。下面是我的结果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"
        }
    ]
  }
]

现在,我想从 user 字段中获得唯一的“ firstName and _id” 字段,并从<< strong>项目字段

1 个答案:

答案 0 :(得分:0)

您可以在mongodb 3.6 及更高版本

中使用以下聚合

使用更新的$lookup语法,您可以在$project管道内使用$lookup ion

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