简体   繁体   English

MongoDB 相当于 Python 的 enumerate()

[英]MongoDB equivalent to Python's enumerate()

I'm searching for a MongoDB aggregation to replace an array我正在寻找一个 MongoDB 聚合来替换一个数组

['a', 'b', 'c']

by something like通过类似的东西

[ {"i":1,"element":"a"}, {"i":2,"element":"b"}, {"i":3,"element":"c"} ]

Thanks谢谢

  • $map to iterate loop of range from 0 to length of lyrics array using $range $map使用$range迭代范围从 0 到lyrics数组长度的循环
  • $add to add 1 in current index because range is started from 0 $add在当前索引中添加 1,因为范围从 0 开始
  • $arrayElemAt to get specific element from lyrics array $arrayElemAtlyrics数组中获取特定元素
db.collection.aggregate([
  {
    $set: {
      lyrics: {
        $map: {
          input: { $range: [0, { $size: "$lyrics" }] },
          in: {
            i: { $add: ["$$this", 1] },
            element: { $arrayElemAt: ["$lyrics", "$$this"] }
          }
        }
      }
    }
  }
])

Playground操场

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

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