Mongodb 聚合管道限制 $lookup 字段

Posted

技术标签:

【中文标题】Mongodb 聚合管道限制 $lookup 字段【英文标题】:Mongodb Aggregation Pipeline limit $lookup fields 【发布时间】:2018-08-06 11:18:20 【问题描述】:

我有两个集合,我试图将它们聚合在一起以产生以下所需的输出,但我正在努力解决如何限制查找返回的数组中的字段。任何帮助将不胜感激。

project

    _id: ObjectId("ABC")    
    projectName: "Project One"


user

    _id: ObjectId("...")
    email: "test1@test.co.uk",
    firstname: "Test1",
    lastname: "Record",
    project: [projectId: ObjectId("ABC")]
,

    _id: ObjectId("...")
    email: "test2@test.co.uk",
    firstname: "Test2",
    lastname: "Record",
    project: [projectId: ObjectId("ABC"), projectId: ObjectId("DEF")]

想要的输出


    projectName: "Project One"
    userDetail: [firstname: "Test1",lastname: "Record", 
            firstname: "Test2",lastname: "Record"]        

目前的工作

db.project.aggregate([$match: _id: ObjectId("ABC") 
,  $lookup: 
                from: "user",
                localField: "_id",
                foreignField: "project.projectId",
                as: "userDetail"
            
 
, $project: _id: 1, projectName: 1
]).pretty()

【问题讨论】:

【参考方案1】:

使用$map$project 阶段映射您选择的字段。


  "$project":
    "projectName":1,
    "userDetail":
      "$map":
        "input":"$userDetail",
        "as":"ud",
        "in":
          "firstname":"$$ud.firstname",
          "lastname":"$$ud.lastname"
        
      
    
  
   

【讨论】:

【参考方案2】:
db.project.aggregate([$match: _id: ObjectId("ABC"), , 
$lookup: 
            from: "user",
            localField: "_id",
            foreignField: "project.projectid",
            as: "userDetail"
        
, $project: _id: 1, projectName:1,"userDetail.firstname":1,"userDetail.lastname":1
]).pretty()

【讨论】:

以上是关于Mongodb 聚合管道限制 $lookup 字段的主要内容,如果未能解决你的问题,请参考以下文章

MongoDB 聚合管道(Aggregation Pipeline)

基于通过 $lookup 检索的字段的多阶段聚合管道匹配数据

MongoDB——聚合管道之$lookup操作

MongoDB——聚合管道之$lookup操作

MongoDB在具有附加字段的对象数组上聚合$lookup

MongoDB在具有附加字段的对象数组上聚合$lookup