一、好言
伤害你的不是对方的绝情,而是你心存幻想的坚持。
二、背景
最近在把一些存mysql的操作的数据,改用nosql存储。所以就涉及到相关mongodb操作,记录如下
三、内容
1、自增id
public <T> T getNextId(String collName ,T clz,String filedName){//指定MG集合名,泛型类,那个字段
Query query = new Query(Criteria.where("collName").is(collName));
Update update = new Update();
update.inc(filedName, 1);
FindAndModifyOptions options = new FindAndModifyOptions();
options.upsert(true);
options.returnNew(true);
T seqId = this.getSqeuence(query, update, options, clz);
return seqId;
}
参考了下该<a href="http://www.jianshu.com/p/3418e32ce757">文章</a>
对于id需要注意,接收类型只支持如下几种,因此接收也需要相应类型。
public <T> T getSqeuence(Query query, Update update, FindAndModifyOptions options , T clz){
return (T)mongoTemplateFactory.getFast().findAndModify(query, update, options, clz.getClass());
}
2、时间
QueryBuilder queryBuilder = new QueryBuilder();
Date date = new Date();
queryBuilder.put("starttime").lessThanEquals(date);
queryBuilder.put("endtime").greaterThanEquals(date);
queryBuilder.put("userId").is(userId);
BasicDBObject fieldsObject = new BasicDBObject();
fieldsObject.put("name","1");
fieldsObject.put("age","1");
fieldsObject.put("sex","1");
fieldsObject.put("address","1");
Query query = new BasicQuery(queryBuilder.get(), fieldsObject);
List<Map> list = mongoBaseServivce.query(query, "MG-USER");
3:更新
Query query = new Query(Criteria.where("_id").is(1));
Update update = Update.update("userName", "haha").set("age", 22)
mongoTemplateFactory.getSafe().updateFirst(query, update, clz, collectionName);
4:排序
query.with(new Sort(new Sort.Order(Sort.Direction.DESC, "id")));