在$ lookup中填充特定字段 [英] Populate specific fields in $lookup

查看:322
本文介绍了在$ lookup中填充特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是我想从结果中填充特定字段,为此,我尝试了 $ project,但是它将projectId组合到一个数组中,将projectName组合到另一个数组中.下面是我的结果json:

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

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

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

推荐答案

您可以将以下聚合与mongodb 3.6 及更高版本一起使用

You can use below aggregation with mongodb 3.6 and above

使用更新的 语法,您可以使用> <

这篇关于在$ lookup中填充特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆