Java与MongoDB的配合使用备忘2-CURD操作具体实例

来源:互联网 发布:一个淘宝店铺卖多少钱 编辑:程序博客网 时间:2024/04/24 06:52

注:代码中出现的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));  




原创粉丝点击