0

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?

Prabhu P
  • 199
  • 1
  • 3
  • 2
    `$pull` is an array operator, but as shown, `items` is an object. – It'sNotMe Nov 22 '21 at 20:12
  • 1
    Any chance of turning `items` into an array in your design...? – Buzz Moschetti Nov 22 '21 at 22:34
  • That sample document isn't valid JSON. you show `day:10` in an array, was that supposed to be an object? As noted it other comments, since `items` is an object, you can't directly use `$pull`, but you might be able to use aggregation to do what you need. – Joe Nov 23 '21 at 01:55
  • Does this answer your question? [How to remove an element from a doubly-nested array in a MongoDB document.](https://stackoverflow.com/questions/5228210/how-to-remove-an-element-from-a-doubly-nested-array-in-a-mongodb-document) – Mayur Vaghasiya Nov 23 '21 at 11:28
  • This is a legacy collection and we are trying to delete the sub items. Also corrected the Json – Prabhu P Nov 23 '21 at 14:25

2 Answers2

0

You could write a JavaScript to achieve this but might depend on the size of the collection.

db.<collection>.find().forEach((doc)=>{
// doc your work on to the doc and upsert the doc
});

You could try with select documents with a criteria to the find query to ensure everything is in place, before running it against all documents.

0

It was much more easier to iterate via cursor, update the required collection and save it to DB.

Prabhu P
  • 199
  • 1
  • 3