以下是我要更新的文档的架构:
{
"field1" : "value1",
"field2" : "value2",
"field3" : {
"list" : [
{
"content" : "valueA",
"start" : "valueA",
"group" : "valueA"
},
{
"content" : "valueB",
"start" : "Needs_Updation",
"group" : "valueB"
},
]
}
Run Code Online (Sandbox Code Playgroud)
我想更新文档的“Needs_Updation”值。
我尝试过以下操作:
db.collection.update({
"field1":"value1" ,
"field3.list" :{"$elemMatch" : {"content" : "valueB","group": "valueB" }}},
{"$set":{"field3.list.$.start" : "Updated_Value"}}
)
Run Code Online (Sandbox Code Playgroud)
还有一个更简单的查询,例如:
db.collection.update({
"field1":"value1" ,
"field3.list.content":"valueB",
{"$set":{"field3.list.$.start" : "Updated_Value"}}
)
Run Code Online (Sandbox Code Playgroud)
我正在使用 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4719 次 |
| 最近记录: |