【问题标题】:MongoDB Aggregation pipeline inner array mappingMongoDB聚合管道内部数组映射
【发布时间】:2020-09-05 16:44:57
【问题描述】:

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

首次收集记录:

{
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】:
    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()
    

    解释在 cmets 中

    【讨论】:

    • 感谢@zishone 感谢您的帮助,显然我真正的数据库结构我的第一条记录也在一个父记录中,父记录>第一条记录>第二条记录。因此,当我对 { parent.field1 : "$parent.field1" } 之类的项目进行分组时,它会为包括“。”的字段路径提供错误。 , 有什么办法可以解决这个问题,谢谢。
    • 在点符号路径中添加引号:'parent.field1'
    猜你喜欢
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多