【问题标题】: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 字段。感谢您的帮助。

【问题讨论】:

    标签: arrays mongodb mongoose aggregation nested-object


    【解决方案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
      }
     }
    ]
    

    【讨论】:

      猜你喜欢
      • 2018-10-15
      • 1970-01-01
      • 2020-05-10
      • 2020-08-09
      • 1970-01-01
      • 2015-11-24
      • 2016-08-17
      • 2021-07-18
      • 2021-10-15
      相关资源
      最近更新 更多