Home > Net >  Unable to remove embedded object from array in Spring Boot MongoDB
Unable to remove embedded object from array in Spring Boot MongoDB

Time:11-30

I have a collection "users", in which contains field "carts" which is array of object. Something like this

{
_id: '61249cb6709f5f61ec6d8372',
name: 'ABC',
carts: [
    {
        cartId: 'cartId-1",
        name: 'test'
    },
    {
        cartId: 'cartId-2",
        name: 'test2'
    }
]

Now I want to remove Object containing "cartId":'cartId-1'. I have tried this -

mongoTemplate.updateMulti(
            Query.query(Criteria.where("id").is("61249cb6709f5f61ec6d8372")),
            new Update().pull("carts", new BasicDBObject("cartId", "cartId-1")),
            Users.class
    );

But it still doesn't remove the embedded object from the array

CodePudding user response:

Try with below code by passing objectid instead of string.

Query.query(Criteria.where("id").is(new ObjectId("61249cb6709f5f61ec6d8372"")))

  • Related