V Manikandan
V Manikandan

Reputation: 370

MongoDB - Update or Create an object in nested Array in Pymongo

This is my collection

{
    "_id" : '50001',
    "data" : 
        [
            {
                    "name" : "ram",
                    "grade" : 'A'
            },
            {
                    "name" : "jango",
                    "grade" : 'B'
            },
            {
                    "name" : "remo",
                    "grade" : 'A'
            }
        ]  
}

Here I want to update the object corresponds to "name": "jango" and have to create a new entry to the Array if "jango" is absent.

I can create a new entry but failed in "create or update".

I tried this way in mongo interpreter

db.MyCollection.update({'_id': '50001', "data.name" :"jango"}, {'$set':{'data': {'data.$.grade':'A'}}}, upsert=true)

but showing

not okForStorage

Upvotes: 3

Views: 1817

Answers (2)

Neo-coder
Neo-coder

Reputation: 7840

Mongo nested update so you should know the position or $ of update values below may help

db.collecionName.update(
   {'_id': '50001', "data.name" :"jango"}, 
   {'$set':{'data.1.grade':'A'}}, upsert=true)

or

   db.collecionName.update(
   {'_id': '50001', "data.name" :"jango"}, 
   {'$set':{'data.$.grade':'A'}}, upsert=true)

Upvotes: 1

vav
vav

Reputation: 4684

You almost there:

db.YourCollection.update(
   { '_id':'50001', <-- to find document
     'data.name': 'jango' < -- to find element of the array
   },
   { '$set': { "data.$.grade" : 'A' } } <-- with .$ you reference array element from first argument
)

Link to documentation

Upvotes: 0

Related Questions