package com.test.mongo; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.bson.Document; import org.bson.conversions.Bson; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.QueryOperators; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.result.DeleteResult; public class MongoDBJDBC { public static void main(String[] args) { try{ @SuppressWarnings("resource") MongoClient client = new MongoClient("localhost",27017); MongoDatabase database = client.getDatabase("testdb"); // System.out.println("连接成功!"+database.getName()); // database.createCollection("test1"); // System.out.println("创建成功:"+database.getCollection("test1").toString()); MongoCollection<Document> collection = database.getCollection("test1"); // Document document = new Document("title", "MongoDB"). // append("description", "database"). // append("likes", 100). // append("by", "Fly"); // long start = System.currentTimeMillis(); // //插入 // List<Document> documents = new ArrayList<Document>(); // SimpleDateFormat sdf=new SimpleDateFormat("yyy-MM-dd hh:mm"); // for(int t = 2 ; t < 24 ; t++) // for(int i = 0 ; i < 1000 ; i ++ ){ // String strDate="2019-06-"+t+" "+(i/60+1)+":"+(i%60); // documents.add(new Document("name", "name"+i). // append("title", "title"). // append("num",i). // append("dates",sdf.parse(strDate) )); // if(i%100000==0){ // collection.insertMany(documents); // documents.clear(); // } // } // collection.insertMany(documents); //insertOne(document); // long end = System.currentTimeMillis(); // System.out.println("time:"+(end-start)); //删 // Bson bson = Filters.eq("description", "database"); // DeleteResult result = collection.deleteMany(bson); // System.out.println("删除数量:"+result.getDeletedCount()); //查 FindIterable<Document> findIterable = collection.find(new BasicDBObject("dates", new BasicDBObject("$gte", sdf.parse("2019-06-1 00:24")) .append("$lte",sdf.parse("2019-06-26 16:24"))) .append("num", new BasicDBObject(QueryOperators.IN, new int[]{1,3,5,7,9}))) .limit(50); // FindIterable<Document> findIterable = collection.find(new BasicDBObject("num", new BasicDBObject(QueryOperators.NIN, new int[]{1,3,5,7,9}))).limit(10); MongoCursor<Document> mongoCursor = findIterable.iterator(); while( mongoCursor.hasNext() ){ Document item = mongoCursor.next(); System.out.println(item.getString("name")+"|"+item.getString("title")+"|"+item.getInteger("num")+"|"+sdf.format(item.getDate("dates"))); } System.out.println("查询结束"); client.close(); }catch (Exception e) { // TODO: handle exception System.err.println(e.getMessage()); } } }
使用的包
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.11.0-beta4</version> </dependency>