MongoDB聚合管道内数组映射

问题描述 投票:0回答:1

我试图在两个集合之间进行如下所示的查找操作。

第一条采集记录。

{
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"
    }
   }
 ]

}

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

mongodb mongodb-query aggregation-framework spring-data-mongodb mongodb-lookup
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()

解释在注释中

© www.soinside.com 2019 - 2024. All rights reserved.