The question I had is posted in stackoverflow. If somebody in this forum knows the answer kindly post solution.
Kindly re-post the question here so that we do not have to navigate into 2 different sites.
The collection I have is like:
[{
"day": 10,
"orders": [{
"id": 1,
"items": {
"uuid1": {
"name": "item1",
"status": false
},
"uuid2": {
"name": "item2",
"status": true
},
"uuid3": {
"name": "item2",
"status": false
}
}
}]
},
{
"day": 11,
"orders": [{
"id": 1,
"items": {
"uuid1": {
"name": "item1",
"status": false
},
"uuid2": {
"name": "item2",
"status": true
},
"uuid3": {
"name": "item2",
"status": false
}
}
}]
}]
I would like to delete items with status marked as true for day 10.
Tried the one below:
db.<collection>.update (
{day: 10},
{ $pull: {
orders: {items: { status: 'true'} } }
},
{multi: true}
);
The result is:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
and so it doesn’t delete.
How should we rewrite this update and pull query so that the items of day 10 marked with status as true are deleted?
Few things first:
I am not sure of what is the expected results.
Do you want the document to become?
// Object uuid2 removed because status:true
{
"day": 10,
"orders": [{
"id": 1,
"items": {
"uuid1": {
"name": "item1",
"status": false
},
"uuid3": {
"name": "item2",
"status": false
}
}
}]
}
// or object with id:1 removed from array orders because one uuid has status:true
{
"day": 10,
"orders": [ ]
},
If uuid2 to be remove then $pull cannot be used because uuid2 is a field inside an object.
If not to late in you model life cycle, I would take a look at Building with Patterns: The Attribute Pattern | MongoDB Blog because the dynamic nature of uuid1, uuid2, … complicates your life.
Thanks Steevej.
The document should become like the first one you listed i.e. “uuid2” removed.
Its a legacy data and I found pull cannot be used but the other option is “$unset” and its very hard to frame a query that can match the value of the key and delete the key.