0

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

首次采集记录:

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

第二次收集记录

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

我正在尝试以以下格式获取输出,以匹配第一个集合中的 field1 名称“FIELD”。

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

}

对于匹配操作后的聚合管道,我仍然坚持如何创建查找操作以检索与第一个映射的第二个集合条目。是否有可能做到这一点或有任何其他方式来实现它?

4

1 回答 1

1
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()

解释在评论中

于 2020-05-19T16:31:25.247 回答