-1
    "_id" : ObjectId("5e2f7ae123227916c02f1ce6"),
    "items" : [     {
            "_id" : ObjectId("5e2f89d63a983002e4562fb2"),
            "item_id" : "123",
            "upc" : "ean"

        },
                {
            "_id" : ObjectId("5e2f89d63a983002e4562fb2"),
            "item_id" : "456",
            "upc" : "ean",

        },
            {
            "_id" : ObjectId("5e2f89d63a983002e4562fb2"),
            "item_id" : "242",
            "upc" : "ean",

        } ]
}

I want to delete multiple object within an items array. The query I am using is..

        db.collection.update({}, {$pull: {items: {item_id: {$in: ["123", "456"] }} } } )

I checked this answer link, which is same as mine. But it didn't work for me.

Appreciate your help.

ravi
  • 1
  • 5

1 Answers1

0

There shouldn't be any issue with your query, Since you've used .update(), it would've updated first found document from result of filter : {'items.item_id': {$in: ["123", "456"] }}, So might have just updated one document out of many matching that filter criteria - which you probably might have missed to observe, Please print the output of that query. As you've nothing mentioned in filter {} - So in case if you wanted to update all documents that match with filter passed in update then use .updateMany() or pass {multi : true} as an option to same .update().

Example :

db.collection.update({}, {$pull: {items: {item_id: {$in: ["123", "456"] }}}}, {multi: true})

(Or)

db.collection.updateMany({}, {$pull: {items: {item_id: {$in: ["123", "456"] }}}})
whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
  • Hi Srinivas, I was trying it in a new collection which has only one document. Also I did try with the filter, but got no success. – ravi Jan 28 '20 at 06:47
  • @ravi : what are you getting with this `db.collection.find({ 'items.item_id': { $in: ["123", "456"] } })` ? As I've mentioned in my first comment did you check are you getting connected to right DB & correct collection ? – whoami - fakeFaceTrueSoul Jan 28 '20 at 06:52
  • I am connecting to the right collection and the right db. Sorry for late reply, was travelling. @whoami – ravi Feb 04 '20 at 19:29
  • @ravi : Did you try executing same query in any client ? robot3T or mongo compass ? – whoami - fakeFaceTrueSoul Feb 04 '20 at 20:21