MongoDB 聚合管道内部数组映射

MongoDB Aggregation pipeline inner array mapping

我正在尝试在两个 collection 之间执行查找操作,如下所示,

前collection条记录:

{
field1: "FIELD",
title: "sometitle",
secondIds: [
  { 
   value: "nestedval1",
   secondId: "234
  }, 
  {
   value: "netedval2,
   secondId: "342"
  }
  ]
}

第二条collection条记录

{
 id: "234", 
 secvalue: "somevalue"
},
{
 id: "342",
 secvalue: "anothervalue"
}

我正在尝试获取以下格式的输出以匹配第一个 collection 中的字段 1 名称 "FIELD"。

{
 field1: "FIELD",
 title: "sometitle",
 secondIds: [
  {
   value: "nestedval1",
   secondId: "234",
   second: {
    id: "234",
    secvalue: "somevalue"
   }
  },
  {
   value: "nestedval2",
   secondId: "342",
   second: {
    id: "342",
    secvalue: "anothervalue"
    }
   }
 ]

}

对于匹配操作后的聚合管道,我仍然停留在如何创建查找操作以检索与第一个映射的第二个 collection 条目。有没有办法做到或者有什么办法可以做到?

firstCollection.aggregate([
  { $unwind: '$secondIds' },           // Lets first separate the secondIds to as different documents
  {
    $lookup: {
      from: 'secondCollection',            // second collection name
      localField: 'secondIds.secondId',    // field in first collection after unwind
      foreignField: 'id',                  // field in second collection
      as: 'secondIds.second'               // field to attach values matched
    }
  },
  { $unwind: '$secondIds.second' },        // attached value after lookup will be an array, so let unwind to make it a object
  { $project: { 'secondIds.second._id': 0 } },  // remove _id
  {
    $group: {
      _id: {                              // grouper fields
        field1: "$field1",
        title: "$title",
      },
      secondIds: { $push: '$secondIds' } // group by pushing to an array
    }
  },
  {
    $project: {                 // projection
      _id: 0,
      field1: '$_id.field1',
      title: "$_id.title",
      secondIds: 1
    }
  }
]).pretty()

解释在评论里