mongodb - 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
但我不知道如何编写它。
解决方案
您可以使用以下聚合管道来做到这一点:
db.posts.aggregate([
{
$set: {
posts: {
$map: {
input: "$posts",
in: {
content: "$$this.content",
timestamp: "$$this.timestamp",
index: { $indexOfArray: ["$posts", "$$this"] }
}
}
}
}
}
])
推荐阅读
- javascript - 使用javascript从输入文本字段中检索json对象值
- python - 我们如何在python中实现Linux命令`sed`?
- javascript - 如何在多个页面中破坏 JSON 数据?
- azure - 无法在 Azure SQL Server (dw) 下找到主数据库
- c# - 是否有一个 isNumeric 函数来确定字符串是否包含数字?
- c++ - Visual Studio Code C++,我想在 cmd 中运行输出
- python - 使用或运算符从字典数组中搜索特定元素
- sql - SQL 更新组中除一条记录外的所有记录
- hyperledger-fabric - 使用结构节点 sdk 注册 Hyperledger Fabric CA TLS 证书
- java - Java,TargetDataLine 读取的字节,将其字节保存到文件的错误代码