mongodb链接有多种;所以不同链接下的api也不太一样。
1、api比较全面
public void query2(){ String mondburl = Config.getInstance().getProperty("mongodb.host"); MongoClientOptions options = new MongoClientOptions.Builder().socketKeepAlive(true).build(); Mongo client = new MongoClient(mondburl, options); DB database = client.getDB("pnr"); DBCollection coll = database.getCollection("b_dep_pnr_flt_test"); DBObject keys = new BasicDBObject(); //条件 DBObject dbObject = new BasicDBObject(); dbObject.put("alnCd", "CZ"); dbObject.put("fltNr", "3452"); dbObject.put("fltDt", "20180425000000"); dbObject.put("arvCd", "SZX"); dbObject.put("depCd", "LJG"); DBObject initial = new BasicDBObject("dcsTimestamp", "0"); String reduce = "function(doc,prev){" + "var docDcsTimestamp=doc.dcsTimestamp;" + "var prevDcsTimestamp=prev.dcsTimestamp;" + "var docDcsTimestampInt=parseInt(docDcsTimestamp);" + "var prevDcsTimestampInt=parseInt(prevDcsTimestamp);" + "if(docDcsTimestampInt > prevDcsTimestampInt){" + "prev.fltNr=doc.fltNr;" + "prev.fltDt=doc.fltDt;" + "prev.dcsTimestamp=doc.dcsTimestamp;}" + "}"; BasicDBList dbList = (BasicDBList) coll.group(keys, dbObject, initial, reduce); //Iterator<Object> iterator = dbList.iterator(); // for (Object object : dbList) { // System.out.println(((DBObject)object).toString()); // } for (Object object : dbList) { BasicDBObject a = (BasicDBObject) object; System.out.println(a.get("fltNr")); } }
2、api不够全的链接
public static MongoClient mongoClient; public static Mongo mongo; private Object object; public static MongoClient connect() { String mondburl = Config.getInstance().getProperty("mongodb.host"); MongoClientOptions options = new MongoClientOptions.Builder().socketKeepAlive(true).build(); if(mongoClient == null) { mongoClient = new MongoClient(mondburl, options); } return mongoClient; }
3、springboot的mongoDb链接