I have some records like:
{ '_id': 1, 'test_field': [{'key1': 'value1'}, {'key2': 'value2'}] }
test_field is a list of dicts. I need to push new dict in that list if any key does not exist and if it does I need to update that key’s value.
Example:
{'key1': 'test_value'}
→ 'test_field': [{'key1': 'test_value'}, {'key2': 'value2'}]
{'test_key': 'test_value2'}
→ 'test_field': [{'key1': 'value1'}, {'key2': 'value2'}, {'test_key': 'test_value_2'}]
Hello @Nikita_Bylnov , welcome to the MongoDB Community forum!
You can do this update using the Updates with Aggregation Pipeline feature. Below is similar post with a solution.:
I want push new object to nested array if object with field ‘Cat’=1 not exists. Or if object with ‘Cat’=1 field exists then increment Up field in this object.
I cant write right syntax, help plz
Document:
{
"BlogId" : 1,
"Items" : [
{
"Cat" : 1,
"Up" : 555,
},
{
"Cat" : 2,
"Up" : 666,
}
]
}
Query (with wrong syntax):
db.exp.update({ BlogId: 1 },
[
{
$set: {
"Items.Cat": {
$cond: [
{ "Items.Cat…
4 Likes