I have a collection, where each document roughly takes the following pattern:
{
"id": 1,
"foo": {
"id": 11,
"barList": [
{
"id": 111,
"name": "Nested Object",
"otherProps": "Continue here"
},
{
"id": 112,
"name": "Nested Object",
"otherProps": "Continue here"
},
{
"id": 113,
"name": "Nested Object",
"otherProps": "Continue here"
}
]
}
}
If possible, in a single operation, I’d like to do an upsert on the array barList
. For example,
if I have a function upsertBar(docId, newBar)
, here is how I’d like it to be have.
Given newBar
as:
{
"id": 113,
"name": "Nested Object Modified",
}
I’d like the collection to be modified as:
{
"id": 1,
"foo": {
"id": 11,
"barList": [
{
"id": 111,
"name": "Nested Object",
"otherProps": "Continue here"
},
{
"id": 112,
"name": "Nested Object",
"otherProps": "Continue here"
},
{
"id": 113,
"name": "Nested Object Modified",
"otherProps": "Continue here"
}
]
}
}
Given newBar
as
{
"id": 114,
"name": "New Fourth Bar",
"otherProps": "Continue here"
}
I’d like the collection to return:
{
"id": 1,
"foo": {
"id": 11,
"barList": [
{
"id": 111,
"name": "Nested Object",
"otherProps": "Continue here"
},
{
"id": 112,
"name": "Nested Object",
"otherProps": "Continue here"
},
{
"id": 113,
"name": "Nested Object",
"otherProps": "Continue here"
},
{
"id": 114,
"name": "New Fourth Bar",
"otherProps": "Continue here"
}
]
}
}
How would I do this with MongoDb?