1. 程式人生 > >java對mongoDB的基本操作 ,遊標使用

java對mongoDB的基本操作 ,遊標使用

odata mat 添加數據 types ava 修改 string 行操作 分別是


package com.mongodb.text; import java.net.UnknownHostException; import java.util.List; import org.bson.types.ObjectId; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.Mongo; import com.mongodb.MongoException; public class MongoDb { //1.建立一個Mongo的數據庫連接對象 static Mongo connection = null; //2.創建相關數據庫的連接 static DB db = null; public MongoDb(String dbName) throws UnknownHostException, MongoException{ connection = new Mongo("127.0.0.1:27017"); db = connection.getDB(dbName); } public static void main(String[] args) throws UnknownHostException, MongoException { //實例化 MongoDb mongoDb = new MongoDb("foobar"); /** * 1.創建一個名字叫javadb的數據庫 */ // mongoDb.createCollection("javadb"); /** * 2.為集合javadb添加一條數據 */ // DBObject dbs = new BasicDBObject(); // dbs.put("name", "uspcat.com"); // dbs.put("age", 2); // List<String> books = new ArrayList<String>(); // books.add("EXTJS"); // books.add("MONGODB"); // dbs.put("books", books); // mongoDb.insert(dbs, "javadb"); /** * 3.批量插入數據 */ // List<DBObject> dbObjects = new ArrayList<DBObject>(); // DBObject jim = new BasicDBObject("name","jim"); // DBObject lisi = new BasicDBObject("name","lisi"); // dbObjects.add(jim); // dbObjects.add(lisi); // mongoDb.insertBatch(dbObjects, "javadb"); /** * 4.根據ID刪除數據 */ // mongoDb.deleteById("502870dab9c368bf5b151a04", "javadb"); /** * 5.根據條件刪除數據 */ // DBObject lisi = new BasicDBObject(); // lisi.put("name", "lisi"); // int count = mongoDb.deleteByDbs(lisi, "javadb"); // System.out.println("刪除數據的條數是: "+count); /** * 6.更新操作,為集合增加email屬性 */ // DBObject update = new BasicDBObject(); // update.put("$set", // new BasicDBObject("eamil","[email protected]")); // mongoDb.update(new BasicDBObject(), // update,false,true,"javadb"); /** * 7.查詢出persons集合中的name和age */ // DBObject keys = new BasicDBObject(); // keys.put("_id", false); // keys.put("name", true); // keys.put("age", true); // DBCursor cursor = mongoDb.find(null, keys, "persons"); // while (cursor.hasNext()) { // DBObject object = cursor.next(); // System.out.println(object.get("name")); // } /** * 7.查詢出年齡大於26歲並且英語成績小於80分 */ // DBObject ref = new BasicDBObject(); // ref.put("age", new BasicDBObject("$gte",26)); // ref.put("e", new BasicDBObject("$lte",80)); // DBCursor cursor = mongoDb.find(ref, null, "persons"); // while (cursor.hasNext()) { // DBObject object = cursor.next(); // System.out.print(object.get("name")+"-->"); // System.out.print(object.get("age")+"-->"); // System.out.println(object.get("e")); // } /** * 8.分頁例子 */ DBCursor cursor = mongoDb.find(null, null, 0, 3, "persons"); while (cursor.hasNext()) { DBObject object = cursor.next(); System.out.print(object.get("name")+"-->"); System.out.print(object.get("age")+"-->"); System.out.println(object.get("e")); } //關閉連接對象 connection.close(); } /** * 穿件一個數據庫集合 * @param collName 集合名稱 * @param db 數據庫實例 */ public void createCollection(String collName){ DBObject dbs = new BasicDBObject(); db.createCollection("javadb", dbs); } /** * 為相應的集合添加數據 * @param dbs * @param collName */ public void insert(DBObject dbs,String collName){ //1.得到集合 DBCollection coll = db.getCollection(collName); //2.插入操作 coll.insert(dbs); } /** * 為集合批量插入數據 * @param dbses * @param collName */ public void insertBatch(List<DBObject> dbses,String collName){ //1.得到集合 DBCollection coll = db.getCollection(collName); //2.插入操作 coll.insert(dbses); } /** * 根據id刪除數據 * @param id * @param collName * @return 返回影響的數據條數 */ public int deleteById(String id,String collName){ //1.得到集合 DBCollection coll = db.getCollection(collName); DBObject dbs = new BasicDBObject("_id", new ObjectId(id)); int count = coll.remove(dbs).getN(); return count; } /** * 根據條件刪除數據 * @param id * @param collName * @return 返回影響的數據條數 */ public int deleteByDbs(DBObject dbs,String collName){ //1.得到集合 DBCollection coll = db.getCollection(collName); int count = coll.remove(dbs).getN(); return count; } /** * 更新數據 * @param find 查詢器 * @param update 更新器 * @param upsert 更新或插入 * @param multi 是否批量更新 * @param collName 集合名稱 * @return 返回影響的數據條數 */ public int update(DBObject find, DBObject update, boolean upsert, boolean multi, String collName){ //1.得到集合 DBCollection coll = db.getCollection(collName); int count = coll.update(find, update, upsert, multi).getN(); return count; } /** * 查詢器(分頁) * @param ref * @param keys * @param start * @param limit * @return */ public DBCursor find(DBObject ref, DBObject keys, int start, int limit, String collName){ DBCursor cur = find(ref, keys, collName); return cur.limit(limit).skip(start); } /** * 查詢器(不分頁) * @param ref * @param keys * @param start * @param limit * @param collName * @return */ public DBCursor find(DBObject ref, DBObject keys, String collName){ //1.得到集合 DBCollection coll = db.getCollection(collName); DBCursor cur = coll.find(ref, keys); return cur; } }




<dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver</artifactId>
        <version>3.2.2</version>
    </dependency>

import java.util.ArrayList;  

import org.bson.Document;
import java.util.List;  
import com.mongodb.MongoClient;  
import com.mongodb.MongoCredential;  
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;  
import com.mongodb.client.FindIterable;  

public class MongodbAppHbaseTest {  
    public static void main(String[] args){  
        try {  
            //連接到MongoDB服務 如果是遠程連接可以替換“localhost”為服務器所在IP地址  
            //ServerAddress()兩個參數分別為 服務器地址 和 端口  
            ServerAddress serverAddress = new ServerAddress("1.1.1.1",27017);  
            List<ServerAddress> addrs = new ArrayList<ServerAddress>();  
            addrs.add(serverAddress);  
              
            //MongoCredential.createScramSha1Credential()三個參數分別為 用戶名 數據庫名稱 密碼  
            MongoCredential credential = MongoCredential.createScramSha1Credential("xxx", "xxx", "xxx".toCharArray());  
            List<MongoCredential> credentials = new ArrayList<MongoCredential>();  
            credentials.add(credential);  
              
            //通過連接認證獲取MongoDB連接  
            MongoClient mongoClient = new MongoClient(addrs, credentials);  
              
            //連接到數據庫  
            MongoDatabase mongoDatabase = mongoClient.getDatabase("name");  
            System.out.println("Connect to database successfully");  
            
//            mongoDatabase.createCollection("xxx");
//            System.out.println("集合創建成功");
            
            MongoCollection<Document> collection = mongoDatabase.getCollection("xxx");
            System.out.println("集合 xxx選擇成功");
            
          //檢索所有文檔  
            /** 
            * 1. 獲取叠代器FindIterable<Document> 
            * 2. 獲取遊標MongoCursor<Document> 
            * 3. 通過遊標遍歷檢索出的文檔集合 
            * */  
            FindIterable<Document> findIterable = collection.find();  
            MongoCursor<Document> mongoCursor = findIterable.iterator();
            int i=0;
            while(mongoCursor.hasNext()){  
               System.out.println(mongoCursor.next());  
               i++;
            }  
            System.out.println("i="+i);
            
        } catch (Exception e) {  
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );  
        }  
    }  
}

 上篇博客介紹了java操作mongoDB進行對文件的處理。現在來介紹一下對文檔的處理。和對文件的處理一樣,也是通過java驅動中提供的幾個類相互作用完成的。這幾個類分別是:

      DBCollection類:指定數據庫中指定集合的實例,提供了增刪改查等一系列操作。在關系型數據庫中,對數據的增刪改查操作是建立在表的基礎上的,在mongodb中是建立在集合的基礎上進行的。

      DBObject接口:DBObject是鍵值的映射,因此,可以將DBObject的實現類作為查詢的返回結果,也可以作為查詢條件

      DBCursor:遊標,返回結果的集合。

    下面是部分實例:


Mongo mongo = new Mongo();
DB db = mongo.getDB("myMongoDB");
DBCollection course = db.getCollection("course");//對myMongoDB數據庫中course集合進行操作



//添加操作
//下面分別是創建文檔的幾種方式:1. .append()  2. .put()   3. 通過map   4. 將json轉換成DBObject對象
DBObject english = new BasicDBObject().append("name","english").append("score", 5).append("id",1);
course.insert(english);
		
DBObject math = new BasicDBObject();
math.put("id", 2);
math.put("name", "math");
math.put("score", 10);
course.insert(math);
		
Map<String,Object> map = new HashMap<String,Object>();
map.put("name","physics" );
map.put("score", 10);
map.put("id", 3);
DBObject physics= new BasicDBObject(map);
course.insert(physics);
		
String json ="{‘name‘:‘chemistry‘,‘score‘:10,‘id‘:4}";
DBObject chemistry =(DBObject)JSON.parse(json);
course.insert(chemistry);
		
List<DBObject> courseList = new ArrayList<DBObject>();
DBObject chinese = new BasicDBObject().append("name","chinese").append("score", 10).append("id", 5);
DBObject history = new BasicDBObject().append("name", "history").append("score", 10).append("id", 6);
courseList.add(chinese);
courseList.add(history);
course.insert(courseList);
      	
//添加內嵌文檔
String json2 =" {‘name‘:‘english‘,‘score‘:10,‘teacher‘:[{‘name‘:‘柳松‘,‘id‘:‘1‘},{‘name‘:‘柳松松‘,‘id‘:2}]}";
DBObject english2= (DBObject)JSON.parse(json);
course.insert(english2);
		
List<DBObject> list = new ArrayList<DBObject>();
list.add(new BasicDBObject("name","柳松").append("id",1));
list.add(new BasicDBObject("name","柳松松").append("id",2));
DBObject english3= new BasicDBObject().append("name","english").append("score",10).append("teacher",list);
		
		
//查詢
//查詢所有、查詢一個文檔、條件查詢
DBCursor cur = course.find();
while(cur.hasNext()){
      DBObject document = cur.next();
      System.out.println(document.get("name"));
  }
      	
DBObject document = course.findOne();
String name=(String)document.get("name");
System.out.println(name);
      	
      	
//查詢學分=5的
DBObject query1 = new BasicDBObject("score",5);
DBObject query2 = new BasicDBObject("score",new BasicDBObject("$gte",5));
DBCursor cur2 = course.find(query2);
//條件表達式:$ge(>)  $get(>=)  $lt(<)  $lte(<=)  $ne(<>)  $in  $nin  $all $exists $or  $nor $where $type等等
      	

//查找並修改		
DBObject newDocument = course.findAndModify(new BasicDBObject("score",5), new BasicDBObject("score",15));

//更新操作		
//q:更新條件  o:更新後的對象
course.update(new BasicDBObject("score",10), new BasicDBObject("test",15));
course.update(new BasicDBObject("score",15), new BasicDBObject("$set",new BasicDBObject("isRequired",true)));
//兩個的區別是,第一個更新是將{"test":15}這個文檔替換原來的文檔,
//第二個更新添加了條件表達式$set,是在原來文檔的基礎上添加"isRequired"這個鍵
//條件表達式:$set  $unset  $push  $inc  $push $push  $addToSet  $pull $pullAll  $pop等等

//當_id相同時,執行save方法相當於更新操作
course.save(new BasicDBObject("name","math").append("_id", 1));
course.save(new BasicDBObject("name","數學").append("_id", 1));

		
		
//刪除符合條件的文檔
course.remove(new BasicDBObject("score",15));
		
//刪除集合及所有文檔
course.drop();
        上面只是介紹了一些簡單的操作,具體復雜的查詢更新可以根據需求再去查找文檔資料。其實,不管操作簡單還是復雜,其核心都是對DBObject和DBCollection的操作,主要掌握DBObject如何構造鍵值對,以及一些條件表達式。

java對mongoDB的基本操作 ,遊標使用