package com.infomorrow.webroot; import java.util.List; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; public class test_mongodb { public static void main(String args[]) throws Exception { MongoClient mongoClient = new MongoClient( "127.0.0.1" , 27017 );//創建鏈接 DB get_db_credit = mongoClient.getDB("credit_2");//數據庫名 DBCollection collection = get_db_credit.getCollection("report");//集合名,對應mysql中的表名 BasicDBObject filter_dbobject = new BasicDBObject(); //創建查詢條件,若是還有其餘條件,相似的寫便可 // 如:version=3,filter_dbobject.put("version", 3),mongod區分String 和 Integer類型,因此要當心"3"!=3 filter_dbobject.put("user_id", "10065716153075"); //下面執行查詢,設置limit,只要10條數據,排序(類mysql orderby) 再建一個BasicDBObject便可,-1表示倒序 DBCursor cursor = collection.find(filter_dbobject).limit(10).sort(new BasicDBObject("create_time",-1)); //把結果集輸出成list類型 List<DBObject> list = cursor.toArray(); System.out.println(list.size());//list的長度 System.err.println(cursor.count());//計算結果的數量,相似於(mysql count()函數),不受limit的影響 //遍歷結果集 while(cursor.hasNext()) { System.out.println(cursor.next()); } } }
補充:1.關於查詢:若是想要查 "a=30或a=50"這樣的條件怎麼辦?mysql
能夠使用$in進行查詢: web
@Test public void testIn(){ //a=30或者a=50 DBObject queryCondition = new BasicDBObject(); BasicDBList values = new BasicDBList(); values.add(30); values.add(50); queryCondition.put("a", new BasicDBObject("$in", values)); DBCursor dbCursor = coll.find(queryCondition); }
2.關於查詢:若是想要查 "a>30或a<10"這樣的條件怎麼辦?sql
能夠使用$or進行查詢: mongodb
@Test public void testOrSingleField(){ DBObject queryCondition = new BasicDBObject(); //查詢a<10 OR a>30
BasicDBList values = new BasicDBList(); values.add(new BasicDBObject("a", new BasicDBObject("$gt", 30))); values.add(new BasicDBObject("a", new BasicDBObject("$lt", 10))); queryCondition.put("$or", values); DBCursor dbCursor = coll.find(queryCondition); }
那麼,若是想要查 "a>30或b<10"這樣的條件怎麼辦?數據庫
只須要將上面代碼改成以下,便可:api
values.add(new BasicDBObject("b", new BasicDBObject("$lt", 10)));
3.若是是多值and查詢只用new BasicDBobject(),而後再put便可,以下所示:app
BasicDBObject basic=new BasicDBObject(); basic.put("name","amosli"); basic.put("hobby","code"); .... collection.find(basic).toArray();//將值轉爲list
4.建立索引函數
// 建立索引 BasicDBObject obj = new BasicDBObject(); obj.put("create_time", -1); collection.ensureIndex(obj); // 查詢索引,遍歷索引 List<DBObject> list = collection.getIndexInfo(); for (DBObject o : list) { System.out.println("\t" + o); }
5.查詢非操做spa
查詢level爲INFO,但status不爲"已完成"的所結果數
//not equal 非操做 BasicDBObject basicDBObject = new BasicDBObject("level","INFO"); System.out.println(collection.count(basicDBObject.append("status", new BasicDBObject("$ne", "已完成"))));
另,可參見:
1.http://blog.csdn.net/llhhyy1989/article/details/12571111
2.http://blog.csdn.net/mydeman/article/details/6652387
3.http://docs.mongodb.org/manual/reference/operator/query/ 查詢命令,$ne,$in