gpt4 book ai didi

mongodb - 使用 Pymongo 更新 MongoDB 中的嵌套文档

转载 作者:行者123 更新时间:2023-12-02 04:20:37 25 4
gpt4 key购买 nike

以下是我要更新的文档的架构:

{

"field1" : "value1",
"field2" : "value2",
"field3" : {
"list" : [
{
"content" : "valueA",
"start" : "valueA",
"group" : "valueA"
},
{
"content" : "valueB",
"start" : "Needs_Updation",
"group" : "valueB"
},
]

}

我想更新文档的“Needs_Updation”值。

我尝试过以下操作:

db.collection.update({
"field1":"value1" ,
"field3.list" :{"$elemMatch" : {"content" : "valueB","group": "valueB" }}},
{"$set":{"field3.list.$.start" : "Updated_Value"}}
)

还有一个更简单的查询,例如:

db.collection.update({
"field1":"value1" ,
"field3.list.content":"valueB",
{"$set":{"field3.list.$.start" : "Updated_Value"}}
)

我正在使用 PyMongo,有没有办法更新此类文档?

最佳答案

您的查询在 shell 中正常运行。您可以尝试以下代码:

import pymongo
#from pymongo import Connection
try:
conn=pymongo.MongoClient()
print "Connected successfully!!!"
db = conn.test #database name = test
collection= db.StackOverflow #collection name= StackOverflow

record= {
"field1" : "value1",
"field2" : "value2",
"field3" : {
"list" : [
{
"content" : "valueA",
"start" : "valueA",
"group" : "valueA"
},
{
"content" : "valueB",
"start" : "Needs_Updation",
"group" : "valueB"
}]
}
}
collection.insert(record)
for data in collection.find():
print "Inserted Data=", data

collection.update({
"field1":"value1" ,
"field3.list" :{"$elemMatch" : {"content" : "valueB","group": "valueB" }}},
{"$set":{"field3.list.$.start" : "Updated_Value"}}
)

for data in collection.find():
print "Updated Data=", data

except pymongo.errors.ConnectionFailure, e:
print "Could not connect to MongoDB: %s" % e
conn

关于mongodb - 使用 Pymongo 更新 MongoDB 中的嵌套文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30782373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com