package com.tesco.mongodb.test;import java.util.List;import java.util.ArrayList;import java.util.logging.Level;import java.util.logging.Logger;import org.bson.Document;import com.mongodb.AggregationOutput;import com.mongodb.BasicDBObject;import com.mongodb.MongoClient;import com.mongodb.client.AggregateIterable;import com.mongodb.client.FindIterable;import com.mongodb.client.MongoCollection;import com.mongodb.client.MongoCursor;import com.mongodb.client.MongoDatabase;public class Test1 { public static void main(String[] args) {Logger log = Logger.getLogger("org.mongodb.driver");log.setLevel(Level.OFF);MongoClient mongoClient = null;MongoCursor<Document> mongoCursor = null;try {Long l1 = System.currentTimeMillis();mongoClient = new MongoClient("xxx.xxx.xxx.xxx", 27017);// create db// MongoDatabase mongoDatabase = mongoClient.getDatabase("testdb");// mongoDatabase.createCollection("testcol");MongoDatabase mongoDatabase = mongoClient.getDatabase("testdb");MongoCollection<Document> collection = mongoDatabase.getCollection("testcol");// create document// Document document = new Document("title", "MongoDB").// append("description", "database2").// append("likes", 100).// append("by", "Fly2");// List<Document> documents = new ArrayList<Document>();// documents.add(document);// collection.insertMany(documents);// update document// collection.updateMany(Filters.eq("likes", 100), new// Document("$set",new Document("likes",200)));// delete document// collection.deleteMany(Filters.eq("likes", 200));//display fieldsBasicDBObject fields = new BasicDBObject();fields.put("_id", 0);//fields.put("title",1);//fields.put("description", 1);//fields.put("likes", 1);//fields.put("by", 1);//query BasicDBObject query = new BasicDBObject();//query.put("description", "database2");query.put("likes", new BasicDBObject("$gt", 0));//sortBasicDBObject sort = new BasicDBObject();//sort.put("by", -1);sort.put("likes", 1);//sort.put("by", 1);//System.out.println(collection.count());FindIterable<Document> findIterable = collection.find(query).sort(sort) .projection(fields) .skip((20000-1)*10).limit(10); mongoCursor = findIterable.iterator();while (mongoCursor.hasNext()) {//System.out.println(mongoCursor.next());Document d = mongoCursor.next();//JSONObject jsonobj = new JSONObject(d.toJson());System.out.println(d.toJson());//String description = (String) jsonobj.get("by");//System.out.println(description);}//BasicDBObject match1 = new BasicDBObject();//BasicDBObject match2 = new BasicDBObject();//List<String> list_query_in = new ArrayList<String>();//list_query_in.add("database1");//list_query_in.add("database2");//match2.put("$in", list_query_in);//match1.put("description", match2);//BasicDBObject match = new BasicDBObject("$match", match1 );//////BasicDBObject p_fields = new BasicDBObject();//p_fields.put("_id", 0);//p_fields.put("description", 1);//p_fields.put("likes", 1);//BasicDBObject project = new BasicDBObject("$project", p_fields ); ////BasicDBObject groupFields = new BasicDBObject("_id", "$description");////BasicDBObject groupFields = new BasicDBObject("_id", null);////groupFields.put("average", new BasicDBObject( "$avg", "$likes"));//102.5//groupFields.put("total", new BasicDBObject( "$sum", "$likes")); //410////groupFields.put("count", new BasicDBObject( "$sum", 1)); // 4//BasicDBObject group = new BasicDBObject("$group", groupFields);////BasicDBObject sort1Fields = new BasicDBObject("total", -1);//BasicDBObject sort1 = new BasicDBObject("$sort", sort1Fields);////List<BasicDBObject> list = new ArrayList<BasicDBObject>();////list.add(match);//list.add(project);//list.add(group);//list.add(sort1);//////aggregate//AggregateIterable<Document> output = collection.aggregate(list);//MongoCursor<Document> mongoCursor1 = output.iterator();//while (mongoCursor1.hasNext()) {//Document d = mongoCursor1.next();//System.out.println(d.toJson());//}Long l2 = System.currentTimeMillis();System.out.println(l2-l1);} catch (Exception e) {e.printStackTrace();} finally {if(null != mongoCursor)mongoCursor.close();if(null != mongoClient)mongoClient.close();}}}
官方連結:http://mongodb.github.io/mongo-java-driver/3.4/driver/tutorials/perform-read-operations/
package com.tesco.mongodb.test;import java.util.Date;import java.util.List;import java.util.ArrayList;import java.util.logging.Level;import java.util.logging.Logger;import org.bson.Document;//import org.json.JSONObject;import com.mongodb.AggregationOutput;import com.mongodb.BasicDBObject;import com.mongodb.Block;import com.mongodb.DBCursor;import com.mongodb.MongoClientURI;import com.mongodb.ReadConcern;import com.mongodb.ReadPreference;import com.mongodb.WriteConcern;import com.mongodb.MongoClient;import static com.mongodb.client.model.Filters.*;import static com.mongodb.client.model.Projections.*;import com.mongodb.client.AggregateIterable;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.model.Sorts;public class Test4 { public static void main(String[] args) {for (int i = 0; i < 3; i++) {run1();}}private static void run1(){Logger log = Logger.getLogger("org.mongodb.driver");log.setLevel(Level.OFF);MongoClient mongoClient = null;MongoCursor<Document> mongoCursor = null;Block<Document> printBlock = new Block<Document>() { @Override public void apply(final Document document) { System.out.println(document.toJson()); }};try {Long l1 = System.currentTimeMillis();/* * MongoClientURI connectionString = new MongoClientURI(" * mongodb://root:****@dds-bp114e3f1fc441342.mongodb.rds.aliyuncs.com:3717, * dds-bp114e3f1fc441341.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-677201"); // ****替換為root密碼MongoClient client = new MongoClient(connectionString); * *///MongoClientURI connectionString = new MongoClientURI("mongodb://myRootAdmin:xxx@" +//MongoClientURI connectionString = new MongoClientURI("mongodb://myTester:xxx@" +//MongoClientURI connectionString = new MongoClientURI("mongodb://myUserAdmin:xxx@" +MongoClientURI connectionString = new MongoClientURI("mongodb://" +"mongodb0.example.net:26001," +"mongodb1.example.net:26002," +"mongodb2.example.net:26003/admin?replicaSet=rs0&maxPoolSize=400");//&readPreference=secondary//&readPreference=nearest//mongodb://host:27017/?replicaSet=rs0&maxPoolSize=200//mongoClient = new MongoClient("10.254.45.223", 27017);//mongoClient = new MongoClient("10.254.45.223", 26001);mongoClient = new MongoClient(connectionString);//mongoClient = MongoDBPoolUtil.pollConnection();//mongoClient.setReadPreference(ReadPreference.secondary());//ReadPreference.nearest();//ReadPreference.primary();//ReadPreference.primaryPreferred();//ReadPreference.secondary();//ReadPreference.secondaryPreferred();//System.out.println(mongoClient.getReadPreference());// create db// MongoDatabase mongoDatabase = mongoClient.getDatabase("testdb");// mongoDatabase.createCollection("testcol1");// get dbMongoDatabase mongoDatabase = mongoClient.getDatabase("test");//MongoDatabase mongoDatabase = mongoClient.getDatabase("local");//.withReadPreference(ReadPreference.secondary())//System.out.println(mongoDatabase.getReadPreference());//mongoDatabase.withReadPreference(ReadPreference.secondary());//mongoDatabase.withWriteConcern(WriteConcern.MAJORITY);//mongoDatabase.withReadConcern(ReadConcern.MAJORITY); //ReadPreference preference = ReadPreference.secondaryPreferred();//MongoCollection<Document> collection = mongoDatabase.getCollection("startup_log");MongoCollection<Document> collection = mongoDatabase.getCollection("testcol123");//MongoCollection<Document> collection = mongoDatabase.getCollection("foo");//.withReadPreference(ReadPreference.secondary());//ReadPreference preference = ReadPreference.primaryPreferred();//System.out.println(collection.getReadPreference());//DBCursor cur = new DBCursor(collection, null, null, preference);//collection.withReadPreference(ReadPreference.secondary());//collection.withWriteConcern(WriteConcern.MAJORITY);//collection.drop(); //create document//List<Document> documents = new ArrayList<Document>();//for (int i = 0; i < 1; i++) {// Document document = new Document("title", "MongoDB").// append("description", "database2").// append("likes", i).// append("by", "Fly"+String.valueOf(i)).// append("long1", Long.valueOf(i)).// append("decimal", new Double("1.9886443895687")).// append("date1", new Date());// documents.add(document);//}//collection.insertMany(documents);//System.out.println(System.currentTimeMillis());//System.out.println(System.nanoTime());//collection.find(eq("a1", 222))collection.find().projection(fields(include("a1", "a2"), excludeId())).sort(Sorts.descending("a2"))//.skip(2).limit(4).forEach(printBlock);//FindIterable<Document> findIterable = collection.find();//mongoCursor = findIterable.iterator();//System.out.println(mongoCursor.hasNext());//while (mongoCursor.hasNext()) {//mongoCursor.next();//System.out.println(mongoCursor.next());//Document d = mongoCursor.next();//System.out.println(d.toJson());//JSONObject jsonobj = new JSONObject(d.toJson());//Long d1 = (Long) jsonobj.getJSONObject("date1").get("$date");//System.out.println(new Date(d1));//} //update document//collection.updateMany(Filters.eq("likes", 5), new Document("$unset",new Document("long2",null)));//// delete document //collection.deleteMany(Filters.eq("likes", 5)));//////display fields//BasicDBObject fields = new BasicDBObject();//fields.put("_id", 0);////fields.put("title",1);////fields.put("description", 1);////fields.put("likes", 1);////fields.put("by", 1);////query //BasicDBObject query = new BasicDBObject();////query.put("description", "database2");////query.put("likes", new BasicDBObject("$lt", 104));////sort//BasicDBObject sort = new BasicDBObject();//sort.put("by", -1);//sort.put("likes", -1);////sort.put("by", 1);//////System.out.println(collection.count());//FindIterable<Document> findIterable = collection.find(query).sort(sort).projection(fields).skip(0).limit(20);//MongoCursor<Document> mongoCursor = findIterable.iterator();//while (mongoCursor.hasNext()) {////System.out.println(mongoCursor.next());//Document d = mongoCursor.next();////JSONObject jsonobj = new JSONObject(d.toJson());//System.out.println(d.toJson());////String description = (String) jsonobj.get("by");////System.out.println(description);//}////BasicDBObject match1 = new BasicDBObject();//BasicDBObject match2 = new BasicDBObject();//List<String> list_query_in = new ArrayList<String>();//list_query_in.add("database1");//list_query_in.add("database2");//match2.put("$in", list_query_in);//match1.put("description", match2);//BasicDBObject match = new BasicDBObject("$match", match1 );////BasicDBObject p_fields = new BasicDBObject();//p_fields.put("_id", 0);//p_fields.put("description", 1);//p_fields.put("likes", 1);//BasicDBObject project = new BasicDBObject("$project", p_fields ); ////BasicDBObject groupFields = new BasicDBObject("_id", "$description");////BasicDBObject groupFields = new BasicDBObject("_id", null);////groupFields.put("average", new BasicDBObject( "$avg", "$likes"));//102.5//groupFields.put("total", new BasicDBObject( "$sum", "$likes")); //410////groupFields.put("count", new BasicDBObject( "$sum", 1)); // 4//BasicDBObject group = new BasicDBObject("$group", groupFields);////BasicDBObject sort1Fields = new BasicDBObject("total", -1);//BasicDBObject sort1 = new BasicDBObject("$sort", sort1Fields);////List<BasicDBObject> list = new ArrayList<BasicDBObject>();//list.add(match);//list.add(project);//list.add(group);//list.add(sort1);////List<BasicDBObject> list = new ArrayList<BasicDBObject>();//BasicDBObject _lookup = new BasicDBObject();//_lookup.put("from", "inventory");//_lookup.put("localField", "item");//_lookup.put("foreignField", "sku");//_lookup.put("as", "inventory_docs");////BasicDBObject _lookup1 = new BasicDBObject();//_lookup1.put("$lookup", _lookup);////list.add(_lookup1);////aggregate//AggregateIterable<Document> output = collection.aggregate(list);//mongoCursor = output.iterator();//while (mongoCursor.hasNext()) {//Document d = mongoCursor.next();//System.out.println(d.toJson());//}//Long l2 = System.currentTimeMillis();System.out.println(l2-l1);} catch (Exception e) {e.printStackTrace();} finally {if(null != mongoCursor)mongoCursor.close();if(null != mongoClient){mongoClient.close();//MongoDBPoolUtil.closeConnection(mongoClient);}}}}