例如,我有一个文档女巫包含以下数组:
...
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
获得当前元素的索引,但我不知道该怎么写。
您可以使用以下聚合管道来实现:
db.posts.aggregate([
{
$set: {
posts: {
$map: {
input: "$posts",
in: {
content: "$$this.content",
timestamp: "$$this.timestamp",
index: { $indexOfArray: ["$posts", "$$this"] }
}
}
}
}
}
])