My task involves updating a json document in mongodb by single field. Despite the simplicity if my data was in an object array, it's more complex due to objects within objects caused by early design choices and reasons.
This is the structure of the single document in my collection:
{
"_id": 123123,
"drivers_teams": {
"drivers" : {
"4" : { <data> },
"5" : { <data indeed> },
...
},
...
}
}
I am aiming to add a new object like this:
const collection = db.get('collection');
let drivers = { };
drivers['111'] = { <new data> };
collection.update({}, {$set: { drivers_teams: { drivers } }}, { upsert: true }, function (err, doc) { ... });
However, the original objects in "drivers_teams" get wiped out and only the new field remains inside.
If I attempt:
collection.update({}, {$set: { drivers }}, { upsert: true }, function (err, doc) { ... });
A new field "drivers" is inserted outside the drivers_teams.
{
"_id": 123123,
"drivers" : { <new data> },
"drivers_teams": { <still original> }
}
I encountered a similar issue (+solution) here but the json wasn't nested like mine. https://groups.google.com/forum/#!topic/mongodb-user/ZxdsuIU94AY
Is there any way to achieve what I'm attempting? Or should I resort to overwriting the entire document when updating a single field?
EDIT
The working solution is
{$set: { 'drivers_teams.drivers.111': <data> }}
. However, what I failed to mention is that the key '111' in the example is actually unknown as it comes from the client while sending update data. This is why the new object was created using this method: dynamically name mongo key field
Any attempts to write something like
{ 'drivers_teams.driver.' + key: <data> }
results in an error.