I was looking through StackOverflow, but most of the questions are related to updating of a single element of the object from the array.
In my case, I have a little different situation. I want to replace full object from an array with a new one.
The original collection looks like:
db.countries.find().pretty()
{
"_id": "some ID goes here",
"longitude": "some longitude",
"latitude": "some latitude",
"name": "name of some country",
"millionaires": [
{"millionaire_id": "ID of the first millionaire",
"name": "name of the first millionaire",
"money": 12000000,
},
{"millionaire_id": "ID of the second millionaire",
"name": "name of the second millionaire",
"money": 15000000,
},
],
}
Then for some reason, I want to replace some data for the first millionaire(amount of money changed, etc.). NOTE: I don't know which field changed.
I'm trying to do something like this:
db.countries.update({"_id": "country ID",
"millionaires.millionaire_id": "ID of the first millionaire"
},
{$set: {
"millionaire_id": "the same millionaire ID",
"value": "should be another value", ...
}
})
But that works unexpectedly:
db.countries.find().pretty();
{
"_id": "some ID goes here",
"longitude": "some longitude",
"latitude": "some latitude",
"name": "name of some country",
"millionaires": [
{"millionaire_id": "ID of the first millionaire",
"name": "name of the first millionaire",
"money": 12000000,
},
{"millionaire_id": "ID of the second millionaire",
"name": "name of the second millionaire",
"money": 15000000,
},
],
{
"millionaire_id": "the same millionaire ID",
"value": "should be another value", ...
}
}
So, it added a new object out of my list of millionaires.
NOTE: objects for updates go programmatically that's why it's not a good idea to try something like this:
new_object = {"millionaires. millionaire_id": "ID", "millionaires.name": "name", ...}
I have raw objects and want to update existing elements using this objects.
Any ideas?