java对MongoDB3.4.2进行增删改条件查询操作

来源:互联网 发布:银行卡四要素 阿里云 编辑:程序博客网 时间:2024/06/06 14:14

一段完整的MongoDB基本操作Demo,实现了连接数据库,进行增删改查操作,其中条件查询实现了与sql中and和or查询

public class MongoDBJDBC {      public static void main(String[] args){      MongoClient mongoClient=null;    BasicDBObject cond=null;    BasicDBList condList =null;        try {              //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址              //ServerAddress()两个参数分别为 服务器地址 和 端口              ServerAddress serverAddress = new ServerAddress("localhost",27017);              List<ServerAddress> addrs = new ArrayList<ServerAddress>();              addrs.add(serverAddress);                            //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码              MongoCredential credential = MongoCredential.createScramSha1Credential("用户名", "用户所属数据库", "密码".toCharArray());              List<MongoCredential> credentials = new ArrayList<MongoCredential>();              credentials.add(credential);                            //通过连接认证获取MongoDB连接              mongoClient = new MongoClient(addrs,credentials);                            //连接到数据库              MongoDatabase mongoDatabase = mongoClient.getDatabase("要获取的数据库名");              System.out.println("Connect to database successfully");                                        //获取集合 参数为“集合名称”              MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("要获取的集合名");              System.out.println("Collection mycol selected successfully");                            //插入文档              /**              * 1. 创建文档 org.bson.Document 参数为key-value的格式              * 2. 创建文档集合List<Document>              * 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List<Document>) 插入单个文档可以用 mongoCollection.insertOne(Document)              * */              Document document = new Document("title", "MongoDB").                      append("description", "database").                      append("likes", 300).                      append("by", "Flyer");              List<Document> documents = new ArrayList<Document>();              documents.add(document);            //增加文档方法            mongoCollection.insertMany(documents);//将含有多个document的List插入到数据库中,可以含有一个或多个,如果只插入一个document也可以用insertOne(document)代替              System.out.println("Document inserted successfully");              //删除符合条件的第一个文档              //mongoCollection.deleteOne(Filters.eq("likes", 200));              //删除所有符合条件的文档              //mongoCollection.deleteMany (Filters.eq("likes", 300));              //检索查看结果              FindIterable<Document> findIterable = mongoCollection.find();            MongoCursor<Document> mongoCursor = findIterable.iterator();              while(mongoCursor.hasNext()){              System.out.println(mongoCursor.next());              }              //条件查询            cond = new BasicDBObject();            condList=new BasicDBList();//BasicDBList和"$in"作为BasicDBObject参数使用,有点类似or
            condList.add((new BasicDBObject("likes", new BasicDBObject("$gt", 100))));            condList.add((new BasicDBObject("likes", new BasicDBObject("$lt", 500))));            cond.put("$or", condList);//多个条件or的实现方法,此处测试MongoDB3.4.2驱动也为3.4.2其中$gt与$gte和$lt与$lte效果一样,可能是bug
            condList.add(300);            condList.add(200);            cond.put("likes",new BasicDBObject("$in",condList));//如果likes字段的值为上面添加到BasicDBList对象condList中的值则符合查询条件            cond.put("by","Flyer");//put多个不同规则相当于and操作            cond.put("likes",200);            cond.put("likes",300);//如果后添加的规则字段是一样的则后面put的查询条件覆盖前面的查询条件            FindIterable<Document> findIterable2 = mongoCollection.find(cond);            MongoCursor<Document> mongoCursor2 = findIterable2.iterator();              System.out.println("以下结果测试and条件查询");            while(mongoCursor2.hasNext()){              System.out.println(mongoCursor2.next());              }              FindIterable<Document> findIterable3 = mongoCollection.find(Filters.eq("likes", 300));//如果只有一个条件可以用这样的形式            MongoCursor<Document> mongoCursor3 = findIterable3.iterator();              System.out.println("以2下2结2果2测2试2条2件2查2询");            while(mongoCursor3.hasNext()){            Document d=mongoCursor3.next();            System.out.println("like的值为"+d.get("likes"));            }          } catch (Exception e) {          System.out.println("MongoDBJDBC.java:出错了出错了出错了");            System.err.println( e.getClass().getName() + ": " + e.getMessage() );          }finally{              mongoClient.close(); //关闭MongoDB的连接         }              }  } 


1 0