$pull with $elemMatch not working


This query works and returns an element.

   {  "items":   {  $elemMatch:  {  productId: "123", productType: "TSHIRT"  }  }  } 

But when I want to remove this item from the items array with the following statement:

This one doesn not work:

db.Cart.updateMany( {  }, { $pull: { "items": { $elemMatch: { "productId": "123", "productType": "TSHIRT" } }  } }

This one works:

db.Cart.updateMany( {  }, { $pull: { "items": { "productType": "TSHIRT", "productId": "123" }  } })

Why is this?

And I am using the JVM (scala driver) - So I need to translate it into Scala code. Still haven’t found a way to do that with the one statement that works.

Please share the element that is returned.

Please share the UpdateResult.

Then run again the first query

to see what was changed.

One of the issue might be that for two objects to be equals the fields must have the same values and be in the same order. The object {a:1,b:2} is not equal to the object {b:2,a:1} because the fields are not in the same order.

Your first query has the order productId and productType. The $pull that does not work has the same order which is surprising because the one that does work has the productType and productId order. I would have guess that the 2nd one does not work but that the first one does.

Ok it’s described in the documentation https://www.mongodb.com/docs/manual/reference/operator/update/pull/#remove-items-from-an-array-of-documents that it won’t work. So no need to pursue this one :slight_smile:

1 Like