0

There I am stuck, how to remove embedded document in mongodb. I am using spring data mongodb criteria, I am doing it like the following:

// database

"_id" : ObjectId("55683d51e4b0b6050c5b0db7"),
    "_class" : "com.samepinch.domain.metadata.Metadata",
    "preferenceType" : "SHOPPING",
    "subtypes" : [
        {
            "_id" : ObjectId("55683d51e4b0b6050c5b0db6"),
            "leftValue" : "VEG",
            "rightValue" : "NON_VEG",
            "preferencePoint" : 0
        }
    ],
    "createdDate" : ISODate("2015-05-29T10:20:01.610Z"),
    "updatedDate" : ISODate("2015-05-29T10:20:01.610Z")


// query

mongoTemplate.updateMulti(new Query(),
                    new Update().pull("subtypes", Query.query(Criteria.where("subtypes._id").is(new objectId("55683d51e4b0b6050c5b0db6"))),Metadata.class);

What i am doing wrong? Thanks in advance!

1 Answer 1

1

subtypes is in nested objects so you should first pass this in $elemMatch is matched first matching array elements of given conditions. Update query as :

db.updateMulti.update({"subtypes":{"$elemMatch":{"_id":ObjectId("55683d51e4b0b6050c5b0db6")}}},
{"$pull":{"subtypes":{"_id":ObjectId("55683d51e4b0b6050c5b0db6")}}})

this query pull exact matching array elements from subtypes array .

And with the help of this spring elemMatch ( not that much expertise in spring mongo ) I converted this query in spring format as below :

mongoTemplate.updateMulti(new Query( 
where("subtypes").elemMatch(where("_id").is(ew objectId("55683d51e4b0b6050c5b0db6"))).pull(
  pull("subtypes", Query.query(Criteria.where("_id").is(new objectId("55683d51e4b0b6050c5b0db6"))),Metadata.class
));

this above spring query not tested I hope you will convert mongo update query in spring mongo query format.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.