I have a document in mongodb with 2 level deep nested array of objects that I need to update, something like this.
{
"id":12362,
"onGoing":[
{
"id":14597,
"offers":[
{
"id":56897,
"status":"validated"
},
{
"id":86127,
"status":"validated"
}
]
},
{
"id":89451,
"offers":[
{
"id":12235,
"status":"validated"
},
{
"id":56457,
"status":"validated"
}
]
}
]
}
I would like to update all offers matching with their id.
I have tried to update like
db.repairJobs.update({
"onGoing.offers":{
$elemMatch:{
_id:{
$in:[
'56897', '56457'
]
}
}
}
},
{
$set:{
"ongoing.offers.$.status":"ACCEPTED"
}
});
But getting the error: cannot use the part (ongoing of ongoing.offers.0.status) to traverse the element ({ongoing: [ { _id: null, ...
Are there any ways to update, the solution need to be compatible with spring Data.
As far as I know there is no way to update documents two level deep in MongoDB. I stumbled upon this JIRA item. I don't think there's a way to use multiple $
operators in update operations.
https://jira.mongodb.org/browse/SERVER-831
I am not aware of any workarounds based on your current schema but I would recommend you to let's say, split your each of your onGoing arrays into different documents.
You can use array filters to do this
Update Nested Arrays in Conjunction with $[]
as for your question, my solution is
db.repairJobs.update(
{},
{
$set: {
"onGoing.$[].offers.$[elem].status": "ACCEPTED"
}
},
{
arrayFilters: [{ "elem.id": {$in: [56897, 56457]} }],
multi: true
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.