首页 > 解决方案 > MongoDB获取数组中当前元素的索引

问题描述

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

...
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

解决方案


您可以使用以下聚合管道来做到这一点:

db.posts.aggregate([
    {
        $set: {
            posts: {
                $map: {
                    input: "$posts",
                    in: {
                        content: "$$this.content",
                        timestamp: "$$this.timestamp",
                        index: { $indexOfArray: ["$posts", "$$this"] }
                    }
                }
            }
        }
    }
])

推荐阅读