MongoDB——Java操作(增刪改查) – JAVA編程語言程序開發技術文章

Java操作MongoDB,下面是一個完整的例子。本實例需導入mongo-2.5.3.jar

Java代碼   
import java.net.UnknownHostException; 
import java.util.Iterator; 
import java.util.Set; 
 
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 MongoMain { 
     
    static DB db = null; 
    static DBCollection coll = null; 
     
    static { 
         Mongo m = null; 
        try { 
            //m = new Mongo();//默認本地 
            //m = new Mongo("127.0.0.1");//默認端口 
            m = new Mongo("127.0.0.1",27017); 
        } catch (UnknownHostException e) { 
            e.printStackTrace(); 
        } catch (MongoException e) { 
            e.printStackTrace(); 
        } 
         
        //獲取名為 test 的數據庫,不存在的情況下創建 
        db = m.getDB("test"); 
         
        //登錄數據庫(用戶名:test,密碼:test) 
        boolean auth = db.authenticate("test", "test".toCharArray()); 
        if(auth){ 
            //隻有admin中的用戶才有此權限(show dbs) 
            //獲取所有數據庫,不顯示無collection的db 
            //System.out.println("所有數據庫名:"+m.getDatabaseNames()); 
             
            //獲取名為 user 的collection(相當於表),不存在的情況下創建 
            coll = db.getCollection("user"); 
        }else{ 
            System.out.println("登錄失敗!"); 
        } 
    } 
     
    public static void main(String[] args) { 
        MongoMain test = new MongoMain(); 
        if(coll!=null){ 
            test.saveData(); 
            test.searchData(); 
            test.updateData(); 
            test.deleteData(); 
        } 
    } 
 
    /**
     * 保存數據
     */ 
    public void saveData(){ 
        //錄入學生1的信息 
        BasicDBObject stu1 = new BasicDBObject(); 
        stu1.put("name", "jack"); 
        stu1.put("age", "25"); 
        BasicDBObject sight1 = new BasicDBObject(); 
        sight1.put("left", 1.5); 
        sight1.put("right", 1.2); 
        stu1.put("sight", sight1); 
         
        //錄入學生2的信息 
        BasicDBObject stu2 = new BasicDBObject(); 
        stu2.put("name", "lucy"); 
        stu2.put("age", "22"); 
        BasicDBObject sight2 = new BasicDBObject(); 
        sight2.put("left", 1.0); 
        sight2.put("right", 1.3); 
        stu2.put("sight", sight2); 
         
        //註意:不能直接對sight賦值{left:1.0,right:1.3} 
         
        coll.insert(stu1); 
        coll.insert(stu2); 
    } 
     
    /**
     * 查詢數據
     */ 
    public void searchData(){ 
        System.out.println("======================="); 
        //show collections 
        //獲取數據庫下所有的collection,不顯示無數據的collection 
        Set<String> colls = db.getCollectionNames(); 
        showData(colls); 
         
        System.out.println("======================="); 
         
        //查詢coll中全部記錄  
        DBCursor ite = coll.find();   
        showData(ite); 
         
        System.out.println("======================="); 
         
        //獲取第一條記錄 
        DBObject o = coll.findOne(); 
        System.out.println(o); 
         
        System.out.println("======================="); 
         
        //統計colletion的數據條數 
        System.out.println(coll.getCount()); 
         
        System.out.println("======================="); 
         
        //查詢 name為jack的對象www.aiwalls.com  
        BasicDBObject query = new BasicDBObject(); 
        query.put("name", "jack"); 
        DBCursor it = coll.find(query);   
        showData(it); 
         
        System.out.println("======================="); 
         
        //查詢age小於30,age不等於20的對象  
        BasicDBObject query2 = new BasicDBObject(); 
        query2.put("age", new BasicDBObject("$lt", 30)); 
        query2.put("age", new BasicDBObject("$ne", 20)); 
        DBCursor it2 = coll.find(query2);   
        showData(it2); 
    } 
     
    /**
     * 修改數據
     */ 
    public void updateData(){ 
        BasicDBObject query = new BasicDBObject(); 
        query.put("name", "lucy"); 
        //這裡的new_info對象一定要是find出的而不是new的,否則多字段的情況下就會丟失其它字段信息 
        DBObject new_info = coll.findOne(query); 
         
        //方法一(缺點,必須把2個值都put進去) 
        BasicDBObject sight = new BasicDBObject(); 
        sight.put("left", 1.3); 
        sight.put("right", 1.3); 
        new_info.put("sight", sight); 
         
        //方法二(優點,隻需設置要修改的字段的值) 
        DBObject obj = (DBObject)new_info.get("sight"); 
        obj.put("right", 1.5); 
         
        coll.update(query, new_info); 
    } 
     
    /**
     * 刪除數據
     */ 
    public void deleteData(){ 
        BasicDBObject data = new BasicDBObject(); 
        //刪除名稱為lucy的記錄 
        data.put("name", "lucy"); 
        //傳入[空實例]刪除所有 
        coll.remove(data); 
    } 
     
    /**
     * 遍歷顯示結果
     * @param result
     */ 
    @SuppressWarnings("rawtypes")  
    public void showData(Iterable result){ 
        Iterator it = result.iterator();  
        while(it.hasNext())   
        {   
            System.out.println(it.next());   
        }   
    }   
}   

摘自  晨曦之光
 

發佈留言