I have collection structure like this.
application_data: {
name : A,
site : B,
location : [
{ key1 : value1, key2 : value2},
{ key3 : value3, key4 : value4}
]
}
Now I want to add a another array to "location" as a sub document so that my location becomes
location : [
{ key1 : value1, key2 : value2},
{ key3 : value3, key4 : value4, key5 :[{subkey1:subvalue1, subkey2:subvalue2}]}
]
I tried $push
& $addToSet
which did not help me. Can somebody help me?
Helpful if you explain an example using nodejs.
What you'r actually trying to do is to add new field to an existing subdocument. You can do it using $set and positional operator $:
db.applications.update({
name: 'A', // querying for parent document
'location.key3': 'value3' // querying for an exact subdocument to add new field to
}, {
$set: {
'location.$.key5': [{
subkey1: 'subvalue1',
subkey2: 'subvalue2'
}]
}
})
You can achieve the same result using $push or $addToSet, which is better if you want to add more than one subsubdocument to 'location.key5'
:
db.applications.update({
name: 'A',
'location.key3': 'value3'
}, {
$push: {
'location.$.key5': {
subkey1: 'subvalue1',
subkey2: 'subvalue2'
}
}
})
or
db.applications.update({
name: 'A',
'location.key3': 'value3'
}, {
$addToSet: {
'location.$.key5': {
subkey1: 'subvalue1',
subkey2: 'subvalue2'
}
}
})
See Update Documents in an Array for more info.