注:代码中出现的MongoDBTemplate类为自定义操作模板类,源码及介绍在上一篇文章中:http://blog.csdn.net/nangongyanya/article/details/72725502
插入文档
MongoCollection<Document> collection = MongoDBTemplate
.getMongoDBTemplate().getCollection(table);
Document document = new Document("title", "MongoDB").
append("description", "database").
append("likes", 100).
append("by", "Fly");
MongoDBTemplate.getMongoDBTemplate().insert(table, document);
检索文档-根据多个条件匹配检索
// 检索所有文档 游标遍历检索出的文档集合
BasicDBObject queryObj = new BasicDBObject();
queryObj.append("sip", sip);
FindIterable<Document> findIterable = collection.find(queryObj)
.limit(criteria.getMaximumResultSize())
.skip(criteria.getFirstResult())
.sort(new BasicDBObject("dateAdded", -1));
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
自定义操作。。。
}
MongoCollection<Document> collection = MongoDBTemplate
.getMongoDBTemplate().getCollection(table);
// 精确匹配检索
Document myDoc1 = collection.find(Filters.eq("ipLong", ipLong)).first();
// 比较匹配检索
Document myDoc2 = collection.find(Filters.eq("dateAdded", new BasicDBObject("$gte", criteria.getStartDate().getTime())).first();
// 模糊匹配检索
Document myDoc3 = collection.find(Filters.eq("type", Pattern.compile("^1.*$", Pattern.CASE_INSENSITIVE)).first();
MongoCollection<Document> collection = MongoDBTemplate
.getMongoDBTemplate().getCollection(table);
//更新文档 将文档中likes=100的文档修改为likes=200
collection.updateMany(Filters.eq("likes", 100), new Document("$set",new Document("likes",200)));
MongoCollection<Document> collection = MongoDBTemplate
.getMongoDBTemplate().getCollection(table);
//删除符合条件的第一个文档
collection.deleteOne(Filters.eq("likes", 200));
//删除所有符合条件的文档
collection.deleteMany (Filters.eq("likes", 200));