Reputation: 415
how to update a field and value in mongodb without replacing the current one? this is the current database
{
"_id": ObjectId('5rac6e8c9cb4081f5c637074')
"name": "crystal"
"color": "green"
"namesOfbooks": {
"redhood": 1,
},
}
i tried this
db.update({name: "crystal"},{ $set: { namesOfbooks: { "cakemaking": 5 } }})
but getting this result below, the previous "redhood": 1
was replace
{
"_id": ObjectId('5rac6e8c9cb4081f5c637074')
"name": "crystal"
"color": "green"
"namesOfbooks": {
"cakemaking": 5,
},
}
how to instead keep the previous "redhood": 1,
with the new "cakemaking": 5
like this below?
{
"_id": ObjectId('5rac6e8c9cb4081f5c637074')
"name": "crystal"
"color": "green"
"namesOfbooks": {
"redhood": 1,
"cakemaking": 5
},
}
Upvotes: 0
Views: 104
Reputation: 17935
It has to be like this :
db.getCollection('YourCollection').update({name: "crystal"},
{ $set: { 'namesOfbooks.cakemaking': 5 }})
but not this :
db.getCollection('YourCollection').update({name: "crystal"},{ $set: { namesOfbooks: { "cakemaking": 5 } }})
Difference would be you're actually updating the attribute namesOfbooks on a whole rather than just update attributes inside namesOfbooks, nested keys inside an object can be accessed via .
notation as like in programming languages.
Upvotes: 1