2

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 ?

4
  • 2
    I just tried your code in the shell and it worked fine. What's not working about it for you? Commented Jun 11, 2015 at 13:42
  • In your second query you missed out } while matching. It should like - db.collection.update({ "field1":"value1" , "field3.list.content":"valueB"}, {"$set":{"field3.list.$.start" : "Updated_Value"}}) ) otherwise your query is right. Commented Jun 11, 2015 at 13:44
  • I don't understand either why the queries are not working on my shell, couldn't find any other way Commented Jun 12, 2015 at 4:57
  • @AsadBaqri What version of MongoDB server are you using? Commented Jun 12, 2015 at 13:18

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.