3

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

2 Answers 2

1

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

3 Comments

But I need to search irrespective of the array index. Only I am able to know the name.
This will not create a new entry to the Array if the searching name does not exist.
for this you should try mongo map reduce it will help you.
0

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

1 Comment

But I just need to create a new entry like {'name': 'jango', 'grade': 'A'} to the array if the name I searching is not there.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.