Reputation: 21
Following is the schema of the document I want to update:
{
"field1" : "value1",
"field2" : "value2",
"field3" : {
"list" : [
{
"content" : "valueA",
"start" : "valueA",
"group" : "valueA"
},
{
"content" : "valueB",
"start" : "Needs_Updation",
"group" : "valueB"
},
]
}
I want to update the "Needs_Updation" value of the document.
I have tried following:
db.collection.update({
"field1":"value1" ,
"field3.list" :{"$elemMatch" : {"content" : "valueB","group": "valueB" }}},
{"$set":{"field3.list.$.start" : "Updated_Value"}}
)
and also a simpler query like:
db.collection.update({
"field1":"value1" ,
"field3.list.content":"valueB",
{"$set":{"field3.list.$.start" : "Updated_Value"}}
)
I'm using PyMongo, is there a way to update this kind of document ?
Upvotes: 2
Views: 5250
Reputation: 637
Your query is working properly in shell. You can try this code:
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
Upvotes: 5