java通过MongoCollection连接mongodb

在springboot版本较低的情况下,无法使用mongotemplate连接数据库,这时候可以使用MongoCollection
具体实现
1、导入maven驱动包

 
            org.mongodb
            mongo-java-driver
            3.0.2
         

2、配置mongo的连接地址

mongo.Host=127.0.0.1
mongo.Port=27017 

3、连接mongo的库和表

 MongoCollection coll = MongoDBUtil.instance.getCollection("Ctrip", "CtripSpiderGrap");
Ctrip是指mongo的库名,CtripSpiderGrap是mongo中的表名。如果库名表名不存在,会自动创建

4、CURD

新增
  coll.insertOne(BsonUtil.toBson(ctripSpiderGrap));
修改
  //修改过滤器,update的条件,arrcity等于100并且depcity等于123
  Bson filter = Filters.and(Filters.eq("arrcity", "100"),Filters.eq("depcity","123"));
  //指定修改的更新文档,更新内容,新的符合条件的arrcity修改为aaa,depcity修改为aaaa
  Document document = new Document("$set", new Document("arrcity", "aaa").append("depcity","aaaa"));
  // 更新一条
  coll.updateOne(filter,document);
  //更新全部
  UpdateResult updateResult = coll.updateMany(filter, document)
  updateResult为返回参数,包含修改的count
删除
  //删除arrcity等于aaa并且depcity等于aaaa的,删除多条
  DeleteResult deleteResult = coll.deleteMany( new Document("arrcity", "aaa").append("depcity","aaaa"));
  //删除单条
  DeleteResult deleteResult = coll.deleteOne( new Document("arrcity", "aaa").append("depcity","aaaa"));
查询
  查询条件,grapstatus != 1
  BasicDBObject filter = new BasicDBObject();
        filter.put("grapstatus",new BasicDBObject("$ne", "1"));
        MongoCursor dbCursor = MongoDBUtil.instance.find(coll,filter);
  //查询结果转json
   while (dbCursor.hasNext()) {
            Document next = dbCursor.next();
            String s = next.toJson();
            CtripSpiderGrap ctripSpiderGrap = JSON.parseObject(s, CtripSpiderGrap.class);
        }

新增
  coll.insertOne(BsonUtil.toBson(ctripSpiderGrap));
修改
  //修改过滤器,update的条件,arrcity等于100并且depcity等于123
  Bson filter = Filters.and(Filters.eq("arrcity", "100"),Filters.eq("depcity","123"));
  //指定修改的更新文档,更新内容,新的符合条件的arrcity修改为aaa,depcity修改为aaaa
  Document document = new Document("$set", new Document("arrcity", "aaa").append("depcity","aaaa"));
  // 更新一条
  coll.updateOne(filter,document);
  //更新全部
  UpdateResult updateResult = coll.updateMany(filter, document)
  updateResult为返回参数,包含修改的count
删除
  //删除arrcity等于aaa并且depcity等于aaaa的,删除多条
  DeleteResult deleteResult = coll.deleteMany( new Document("arrcity", "aaa").append("depcity","aaaa"));
  //删除单条
  DeleteResult deleteResult = coll.deleteOne( new Document("arrcity", "aaa").append("depcity","aaaa"));
查询
  查询条件,grapstatus != 1
  BasicDBObject filter = new BasicDBObject();
        filter.put("grapstatus",new BasicDBObject("$ne", "1"));
        MongoCursor dbCursor = MongoDBUtil.instance.find(coll,filter);
  //查询结果转json
   while (dbCursor.hasNext()) {
            Document next = dbCursor.next();
            String s = next.toJson();
            CtripSpiderGrap ctripSpiderGrap = JSON.parseObject(s, CtripSpiderGrap.class);
        }

你可能感兴趣的:(java通过MongoCollection连接mongodb)