Reputation: 370
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
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
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
)
Upvotes: 0