arrays - 如何在 mongodb 中对深度嵌套的 JSON 执行更新查询?
问题描述
我在 mongodb 中有一个嵌套的 json 数据结构,如下所示:
{
'tid': 1,
'matches': [{
'dord': 1,
'matches': [{
'tord': 1,
'score': 11
},
{
'tord': 2,
'score': 12
}
]
},
{
'dord': 2,
'matches': [{
'tord': 1,
'score': 21
},
{
'tord': 2,
'score': 22
}
]
}]
}
我想用"dord": 1
and更新行"tord": 1
并将值score
从11更改为100。我该怎么做呢?
我已经尝试过的:
db.collection.update({'tid': 1}, {'matches': {$elemMatch: {'dord': 1}}}, {'matches': { $elemMatch: {'tord': 1}}}, {'score': 100})
解决方案
演示 - https://mongoplayground.net/p/Mi2HnhzkPpE
https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/
过滤的位置运算符 $[] 标识与更新操作的 arrayFilters 条件匹配的数组元素
db.collection.update({ "tid": 1 },
{ $set: { "matches.$[m].matches.$[t].score": 100 } },
{
arrayFilters: [
{ "m.dord": 1 }, // to match where dord = 1
{ "t.tord": 1, "t.score": 11 } // and where tord = 1 and score = 11
]
})
推荐阅读
- jquery - 通过 JQuery 使用 SlideDown 和 SlideUp 更改图标
- c++ - 有人可以解释一下,为什么这段代码不需要函数定义?
- c# - DataGrid datagridComboxColumn 不显示值
- vue.js - 如何使用 content-type:application/json 在 vue 中跳过 Preflight Requset
- adsense - Adsense - 我们发现您的网站已关闭或不可用
- mysql - SQL FOREIGN KEY CONSTRAINT 命名差异
- virtual-machine - Oracle VirtualBox - 无法导入图像
- bash - How to iterate through an array to populate buttons for AppleScript dialog?
- python-3.x - 如何将带有不需要的字符('[','“')的字符串转换为列表?
- java - 如何在测试调试期间访问 H2 数据库控制台