Reputation: 2403
In my project I'm using SpringBoot 1.3.2 and org.springframework.data.mongodb.core.query.*
I'm trying to remove element from nested object array, in my main object i have array looking like this:
"sections" : [
{
"sectionId" : "56cc3c908f5e6c56e677bd2e",
"name" : "Wellcome"
},
{
"sectionId" : "56cc3cd28f5e6c56e677bd2f",
"name" : "Hello my friends"
}
]
Using Spring I want to delete record with sectionId 56cc3c908f5e6c56e677bd2e
This is way I'm trying do this:
Query query = Query.query(Criteria
.where("sections")
.elemMatch(
Criteria.where("sectionId").is("56cc3c908f5e6c56e677bd2e")
)
);
Update update = new Update().unset("sections.sectionId");
mongoTemplate.updateMulti(query, update, Offer.class);
Query is finding propper element but there is something wrong with Update and I don't know what so removing is not working.
Could any body can help me with this?
Upvotes: 1
Views: 4420
Reputation: 1
I don't think the accepted answer necessarily works for all cases with BAsicDbObject class. Springboot would need the the class of the object you are trying to pull/delet in order for it to properly map it, so here is how I did it:
var sectionToRemove = new Section()
. sectionId("56cc3c908f5e6c56e677bd2e");
var updateAction = new Update().pull("sections", sectionToRemove);
var res = mongoOps.updateMulti(query, updateAction, Section.class);
Upvotes: 0
Reputation: 2403
There is no need for query
Update update =
new Update().pull("sections",
new BasicDBObject("sectionId", "56cc3c908f5e6c56e677bd2e"));
mongoTemplate.updateMulti(new Query(), update, Offer.class);
That solution is perfectly working.
Upvotes: 3
Reputation: 180877
Since I need the practice anyway, here's a guess to as what you want.
Query query = Query.query(Criteria
.where("sections")
.elemMatch(
Criteria.where("sectionId").is("56cc3c908f5e6c56e677bd2e")
)
);
Update update =
new Update().pull("sections",
new BasicDBObject("sectionId", "56cc3c908f5e6c56e677bd2e"));
mongoTemplate.updateMulti(query, update, Offer.class);
resulting in
"sections" : [
{
"sectionId" : "56cc3cd28f5e6c56e677bd2f",
"name" : "Hello my friends"
}
]
Upvotes: 5