Easy life with Spring Data Mongodb Criteria
Posted By : Prabjot Singh | 07-Jun-2015
Mongodb is famous for ignoring table joins,so we can save document inside other document called embedded document. I saw many people confuse about how to queries on embedded document. So I will show you how can easily you can update delete embedded document using mongotemplate. for this I will use mongotemplate query,because I am more comfortable with mongotemplate.
I am considering you know about how to configure spring data mongodb in project. If you don't know you can find at my blog Configure Spring Data Mongodb
So my domain design looks like
public class Metadata extends BaseEntity { private MetadataEnum preferenceType; Listsubtypes = new ArrayList (); public MetadataEnum getPreferenceType() { return preferenceType; } public void setPreferenceType(MetadataEnum preferenceType) { this.preferenceType = preferenceType; } public List getSubtypes() { return subtypes; } public void setSubtypes(List subtypes) { this.subtypes = subtypes; } }
and my database looks like
{
"_id" : ObjectId("556d5853e4b0c91c189d7e02"),
"_class" : "com.samepinch.domain.metadata.Metadata",
"preferenceType" : “food”,
"username" : "[email protected]",
“subtypes”:[{
"_id" : ObjectId("556d5853e4b0c91c189d7e03"),
“type”:”burger”
}]
}
There,my subdocument is subtypes,so I will perofrm operations on subtype document which in embedded in users collection.
Update Embedded document
Here I will update type of subtypes using mongotemplate criteria.
Query query = new Query(Criteria.where("id").is(new ObjectId(“556d5853e4b0c91c189d7e02”))
.and("subtypes.id").is(new ObjectId(“556d5853e4b0c91c189d7e03”)));
Update update = new Update.update("preferenceType",
metadata.getPreferenceType());
update.set("subtypes.$.type ",”noodles”);
mongoTemplate.updateFirst(query, update, Metadata.class);
Delete Embedded document
Query query = new Query(Criteria.where("subtypes").elemMatch(
Criteria.where("_id").is(new ObjectId(“556d5853e4b0c91c189d7e03”))));
Update update = new Update().pull("subtypes",
new Query(Criteria.where("_id").is(new ObjectId(“556d5853e4b0c91c189d7e03”))));
mongoTemplate.updateMulti(query, update, Metadata.class);
Thanks !!!
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Prabjot Singh
Prabjot is a Java and Grails developer.He has a good hands on neo4J, AngularJS. He likes to work on new technologies