For example, I have a user class, which contains a label attribute. This label is an array, and the elements in the array are embedded documents. The format is as follows:
{
“_id” : “195861”,
“tags” : [
{
“tagId” : NumberLong(766),
“optDate” : ISODate(“2013-08-12T15:21:02.930Z”),
“enable” : true
},
{
“tagId” : NumberLong(778),
“optDate” : ISODate(“2013-08-12T15:21:02.930Z”),
“enable” : true
}
]
}
Next, add, delete and check tags in this document. Spring mongodb is used here.
MongoTemplate class inside. Here I abstract the embedded documents in tags into the Tag class. Code deletion and modification itself contains query methods, so no query methods are written.
/**
*
* @author zhangdonghao
*
*/
@Component(“UserrTagServiceImpl”)
public class UserrTagServiceImpl implements UserrTagService {
/**
* Mongo DB Spring Template
*/
@Resource
protected MongoTemplate mOngoTemplate= null;
public UserrTagServiceImpl() {
}
/**
**Add an element to the tags array
*/
@Override
public Response addTag(String id, Long tagId) {
Try {
Tag tag = new Tag(tagId);
tag.setOptDate(new Date());
tag.setEnable(true);
Query query =
Query.query(Criteria.where(“_id”).is(id));
Update update = new Update();
update.addToSet(“tags”, tag);
mongoTemplate.upsert(query, update,
User.class);
} catch (Exception e) {
Return new
Response(0);
}
Return new Response(1);
}
/**
**Modify the value of an element specified by the embedded document in the tags array
*/
@Override
public Response disableTag(String id, Long tagId)
{
Try {
Query query =
Query.query(Criteria.where(“_id”).is(id)
.and(“tags.tagId”).is(tagId));
Update update = new Update();
update.set(“tags.$.enable”, false);
mongoTemplate.updateFirst(query,
update, User.class);
} catch (Exception e) {
Return new
Response(0);
}
Return new Response(1);
}
/**
**Delete the embedded document specified in the tags array
*/
@Override
public Response removeTag(String id, Long tagId)
{
Try {
Query query =
Query.query(Criteria.where(“_id”).is(id)
.and(“tags.tagId”).is(tagId));
Update update = new Update();
update.unset(“tags.$”);
mongoTemplate.updateFirst(query,
update, User.class);
} catch (Exception e) {
Return new
Response(0);
}
Return new Response(1);
}
public MongoTemplate getMongoTemplate() {
Return mongoTemplate;
}
public void setMongoTemplate(MongoTemplate mongoTemplate) {
This.mOngoTemplate= mongoTemplate;
}
}