简体   繁体   English

MongoDB 阵列内的 $project

[英]$project inside MongoDB array

I have MongoDB collection items with following document:我有 MongoDB 收集items与以下文件:

{
    data: [{"name": "First"}, {"name": "Second"}],
    data2: [{"value": 20}, {"value": 30}]
}

Is there any way to project data2.value into data.value on same indexes?有没有办法将data2.value投影到同一索引上的data.value中? I would need this result:我需要这个结果:

{
    data: [
        {"name": "First", value: 20},
        {"name": "Second", value: 30}
    ]
}

It would like something like that:它想要这样的东西:

db.items.aggregate([{"$project": {"data.X.value": "$data2.X.value", "data2": 0}}]) // Where X "iterate" over all indexes (so 0 and 1).

Lengths of arrays data and data2 are always same, but it doesn't have to be 2. arrays datadata2的长度始终相同,但不必为 2。

You can try,你可以试试,

  • $map to loop through object by object of data array $map通过data数组的 object 循环遍历 object
  • $indexOfArray to get the index of current object $$d $indexOfArray获取当前 object 的索引$$d
  • $arrayElemAt to get the element value of data2 from particular $$d object index $arrayElemAt从特定$$d object 索引中获取data2的元素value
db.collection.aggregate([
  {
    $project: {
      data: {
        $map: {
          input: "$data",
          as: "d",
          in: {
            name: "$$d.name",
            value: {
              $arrayElemAt: [
                "$data2.value",
                { $indexOfArray: ["$data", "$$d"] }
              ]
            }
          }
        }
      }
    }
  }
])

Playground: https://mongoplayground.net/p/wv1vEVsrHeT游乐场: https://mongoplayground.net/p/wv1vEVsrHeT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM