MongoDB获取数组中当前元素的索引

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

例如,我有一个文档女巫包含以下数组:

...
posts: [
   {
      "content": "this is a post",
      "timestamp": 1242345,
   },
   {
      "content": "this is a second post",
      "timestamp": 1243345,
   }
]
....

我如何编写find查询以获取此结果:

...
posts: [
   {
      "content": "this is a post",
      "timestamp": 1242345,
      "index": 0
   },
   {
      "content": "this is a second post",
      "timestamp": 1242345,
      "index": 1
   }
]
....

我的想法是用$addFields添加一个新字段,然后用$indexOfArray获得当前元素的索引,但我不知道该怎么写。

mongodb
1个回答
0
投票

您可以使用以下聚合管道来实现:

db.posts.aggregate([
    {
        $set: {
            posts: {
                $map: {
                    input: "$posts",
                    in: {
                        content: "$$this.content",
                        timestamp: "$$this.timestamp",
                        index: { $indexOfArray: ["$posts", "$$this"] }
                    }
                }
            }
        }
    }
])
© www.soinside.com 2019 - 2024. All rights reserved.