【发布时间】:2021-05-09 18:00:07
【问题描述】:
我有一些这样的文件:
doc = {
"tag" : "tag1",
"field" : {
"zone" :"zone1",
"arr" : [
{ vals: [-12.3,-1,0], timestamp: ""},
{ vals: [-30.40,-23.2,0], timestamp: "" }
]
}
}
我想修改其中一个文档的数组元素之一(例如,第一个元素,索引为 0 的元素)。
我想让它看起来像:
doc = {
"tag" : "tag1",
"field" : {
"zone" :"zone1",
"arr" : [
{ vals: [-1, -1, -1], timestamp: "the_new_timestamp"}, // this one was modified
{ vals: [-30.40, -23.2, 0], timestamp: "" }
]
}
}
我对@987654325@有所了解:
db.mycollection.find_and_modify(
query = query, // you find the document of interest with this
fields = { }, // you can focus on one of the fields of your document with this
update = { "$set": data }, // you update your data with this
)
感觉更接近我想要的问题是:
我一直在研究它们,但在尝试为我的案例制定解决方案时遇到了困难。我不知道我是否真的应该使用fields 参数。我不知道如何正确使用$set。
希望你能帮助我。
【问题讨论】:
-
查询
query = query是什么?如何判断需要修改哪个元素? -
哦,对了,我错过了。查询将过滤掉一个或多个文档,假设我只得到一个结果。然后我想通过它的索引选择一个数组元素。
标签: mongodb mongodb-query pymongo