mongodb - MongoDB 如何在嵌套结构中查找和更新数据
问题描述
我的 mongoDB (v3.6.4) 有问题,下面是我的数据现在的样子。我需要在“second_list”中找到(并更新)某个元素的“text”值,即返回“hello”并在下一步将其更改为“hello world”。
{
"_id": ObjectId("xxxxxxxxxxxxx"),
"top_list": [
{
"create_time": "2019-06-10 15:56:46",
"second_list": [
{
"name": "v1",
"text": "hello"
},
{
"name": "v2",
"text": "good morning"
},
{
"name": "v3",
"text": "bye"
}
]
}
]
}
我试过这个查询
db.myCollection.find(
{'top_list.second_list.name':'v1'},
{"top_list.second_list":1,"_id":0}
)
但它返回了整个“second_list”。我想要的应该是
{
"name": "v1",
"text": "hello"
}
或者只是字符串“hello”。
解决方案
此语法适用于我查找和更新值
db['myCollection'].findAndModify({query:{_id: ObjectId("xxxxxxxxxxxxx")}, update: {$set: {"top_list.second_list.0.text":"someNewText"}}})
0 intop_list.second_list.0.text
是您要访问的数组索引
推荐阅读
- python - 烧瓶中表单的提交按钮不起作用
- java - Checking for space in an edittext
- java - 添加 actionPerformed 后组合框中的项目减少
- react-native - 如何在 react-native 中从 Firebase 设置 sendSignInLinkToEmail()?
- r - chartJSRadar 下载处理程序创建空 png
- python - python中的整数多项式的根
- scala - 在 Spark 中读取 gpkg 格式
- java - 用于计算两个数字的 GCD 和 LCM 的 Java 代码工作正常,但在其中一个在线平台上不被接受
- node.js - Nodejs请求解析特殊字符
- wordpress - 将整个商店前缀重定向到另一个没有插件的地方