如何仅在猫鼬中使用聚合填充嵌套在对象数组中的字段?

Posted

技术标签:

【中文标题】如何仅在猫鼬中使用聚合填充嵌套在对象数组中的字段?【英文标题】:How do I populate a field nested in array of objects using aggregation only in mongoose? 【发布时间】:2021-10-16 10:05:55 【问题描述】:

我试图在数组中填充一个深度嵌套的对象已经有一段时间了,但没有运气。我尝试展开数组,但结果数组被转换为对象而不是数组。

let aggQuery: any = [
             $match:  
    
            
                $lookup: 
                    from: "tribe-answers", localField: "answers", foreignField: "_id", as: "answers"
                
            ,
             
                "$unwind": 
                "path": "$answers.createdBy",
                "preserveNullAndEmptyArrays": true
                
            ,
            
            $lookup: 
                from: "users", localField: "answers.createdBy", foreignField: "_id", as: "answers.createdBy"
            
            ,
            
        ];

预期输出

answers = [
  _id,
  content
  createdBy
     _id
     firstname
     lastname
  
 ,
  _id,
  content
  createdBy
     _id
     firstname
     lastname
  
 
]

返回的输出

answers = 
   _id,
  content
  createdBy
     _id
     firstname
     lastname
  
 

上述查询确实填充了 createdBy 字段,但将数组转换为对象。我需要的是在答案数组的每个元素中填充 createdBy 字段。感谢您的帮助。

【问题讨论】:

【参考方案1】:
db.getCollection('tribe-posts').aggregate([
     
        "$lookup": 
           "from": "tribe-answers",
            "let": answerIds: "$answers",
            "pipeline": [
                 "$match":  "$expr":  "$in": [ "$_id", "$$answerIds" ]   ,
                $lookup:  from: "users", localField: "createdBy", foreignField: "_id", as: "createdBy" ,
                "$unwind": "path": "$createdBy","preserveNullAndEmptyArrays": true 
                
            ],
            "as": "answers"
            
    ,
])

这将产生预期的输出

answers = [
  _id,
  content
  createdBy
     _id
     firstname
     lastname
  
 ,
  _id,
  content
  createdBy
     _id
     firstname
     lastname
  
 
]

【讨论】:

以上是关于如何仅在猫鼬中使用聚合填充嵌套在对象数组中的字段?的主要内容,如果未能解决你的问题,请参考以下文章

如何在猫鼬中更新嵌套数组值

如何在猫鼬中填充嵌套实体?

如何使用聚合在猫鼬中对文档数组进行分页?

在猫鼬中填充+聚合[重复]

如何通过填充字段在猫鼬中查找文档?

如何通过填充字段在猫鼬中查找文档?