Java操做MongoDB

1、準備工做

一、 首先,下載mongoDB對Java支持的驅動包 html

驅動包下載地址:https://github.com/mongodb/mongo-java-driver/downloadsjava

mongoDB對Java的相關支持、技術:http://www.mongodb.org/display/DOCS/Java+Language+Centergit

驅動源碼下載:https://download.github.com/mongodb-mongo-java-driver-r2.6.1-7-g6037357.zipgithub

在線查看源碼:https://github.com/mongodb/mongo-java-drivermongodb

二、 下面創建一個JavaProject工程,導入下載下來的驅動包。便可在Java中使用mongoDB,目錄以下: 數據庫

clip_image002

 

2、Java操做MongoDB示例

在本示例以前你須要啓動mongod.exe的服務,啓動後,下面的程序才能順利執行; app

 

一、 創建SimpleTest.java,完成簡單的mongoDB數據庫操做 ide

Mongo mongo = new Mongo(); spa

這樣就建立了一個MongoDB的數據庫鏈接對象,它默認鏈接到當前機器的localhost地址,端口是27017。 .net

DB db = mongo.getDB(「test」); 

這樣就得到了一個test的數據庫,若是mongoDB中沒有建立這個數據庫也是能夠正常運行的。若是你讀過上一篇文章就知道,mongoDB能夠在沒有建立這個數據庫的狀況下,完成數據的添加操做。當添加的時候,沒有這個庫,mongoDB會自動建立當前數據庫。 

獲得了db,下一步咱們要獲取一個「彙集集合DBCollection」,經過db對象的getCollection方法來完成。 

DBCollection users = db.getCollection("users"); 

這樣就得到了一個DBCollection,它至關於咱們數據庫的「表」。 

查詢全部數據 

DBCursor cur = users.find(); 

while (cur.hasNext()) { 

System.out.println(cur.next()); 

 1 import java.net.UnknownHostException;
 2 
 3 import com.mongodb.DB;
 4 import com.mongodb.DBCollection;
 5 import com.mongodb.DBCursor;
 6 import com.mongodb.Mongo;
 7 import com.mongodb.MongoException;
 8 import com.mongodb.util.JSON;
 9 public class SimpleTest {
10     public static void main(String[] args) throws UnknownHostException, MongoException {  
11         Mongo mg = new Mongo();        //查詢全部的Database        
12         for (String name : mg.getDatabaseNames()) { 
13             System.out.println("dbName: " + name);     
14         }                
15         DB db = mg.getDB("test");        //查詢全部的彙集集合       
16         for (String name : db.getCollectionNames()) { 
17             System.out.println("collectionName: " + name);       
18         }                
19         DBCollection users = db.getCollection("users");                //查詢全部的數據        
20         DBCursor cur = users.find();       
21         while (cur.hasNext()) {  
22             System.out.println(cur.next());      
23         }        
24         System.out.println(cur.count());        
25         System.out.println(cur.getCursorId());        
26         System.out.println(JSON.serialize(cur));    
27     }
28 }
View Code

 

二、 完成CRUD操做,CRUD是指在作計算處理時的增長(Create)、讀取(Retrieve)(從新獲得數據)、更新(Update)和刪除(Delete)幾個單詞的首字母簡寫。創建一個MongoDB4CRUDTest.java

  1 import java.net.UnknownHostException;
  2 import java.util.ArrayList;
  3 import java.util.List;
  4 import org.bson.types.ObjectId;
  5 import com.mongodb.BasicDBObject;
  6 import com.mongodb.Bytes;
  7 import com.mongodb.DB;
  8 import com.mongodb.DBCollection;
  9 import com.mongodb.DBCursor;
 10 import com.mongodb.DBObject;
 11 import com.mongodb.Mongo;
 12 import com.mongodb.MongoException;
 13 import com.mongodb.QueryOperators;
 14 import com.mongodb.util.JSON; 
 15 
 16 public class MongoDB4CRUDTest {       
 17     private Mongo mg = null;    
 18     private DB db;    
 19     private DBCollection users;        
 20  
 21     public void init() {        
 22         try {            
 23             mg = new Mongo();  
 24             //mg = new Mongo("localhost", 27017);       
 25             } 
 26         catch (UnknownHostException e) {
 27                 e.printStackTrace();        
 28         } catch (MongoException e) 
 29         { 
 30                     e.printStackTrace();       
 31         }        
 32         //獲取temp DB;若是默認沒有建立,mongodb會自動建立       
 33         db = mg.getDB("temp");        
 34         //獲取users DBCollection;若是默認沒有建立,mongodb會自動建立       
 35         users = db.getCollection("users");    
 36     }           
 37         
 38     public void destory() {        
 39             if (mg != null)            
 40                 mg.close();        
 41             mg = null;        
 42             db = null;        
 43             users = null;        
 44             System.gc();    
 45     }        
 46     public void print(Object o) { 
 47             System.out.println(o);    
 48     }
 49 
 50     /** 
 51       
 52      * <b>function:</b> 查詢全部數據 
 53        
 54      */  
 55        
 56     private void queryAll() {  
 57        
 58         print("查詢users的全部數據:");  
 59        
 60         //db遊標  
 61        
 62         DBCursor cur = users.find();  
 63        
 64         while (cur.hasNext()) {  
 65        
 66             print(cur.next());  
 67        
 68         }  
 69        
 70     }  
 71 
 72        
 73     public void add() {  
 74        
 75         //先查詢全部數據  
 76        
 77         queryAll();  
 78        
 79         print("count: " + users.count());  
 80         
 81         DBObject user = new BasicDBObject();  
 82        
 83         user.put("name", "hoojo");  
 84        
 85         user.put("age", 24);  
 86        
 87         //users.save(user)保存,getN()獲取影響行數  
 88        
 89         //print(users.save(user).getN());  
 90        
 91            
 92         //擴展字段,隨意添加字段,不影響現有數據  
 93        
 94         user.put("sex", "男");  
 95        
 96         print(users.save(user).getN());  
 97         
 98         //添加多條數據,傳遞Array對象  
 99        
100         print(users.insert(user, new BasicDBObject("name", "tom")).getN());  
101         
102         //添加List集合  
103        
104         List<DBObject> list = new ArrayList<DBObject>();  
105        
106         list.add(user);  
107        
108         DBObject user2 = new BasicDBObject("name", "lucy");  
109        
110         user.put("age", 22);  
111        
112         list.add(user2);  
113        
114         //添加List集合  
115        
116         print(users.insert(list).getN());  
117        
118         //查詢下數據,看看是否添加成功  
119        
120         print("count: " + users.count());  
121        
122         queryAll();  
123        
124     }  
125         
126       
127 //刪除數據   
128        
129     public void remove() {  
130        
131         queryAll();  
132        
133         print("刪除id = 4de73f7acd812d61b4626a77:" + users.remove(new BasicDBObject("_id", new ObjectId("4de73f7acd812d61b4626a77"))).getN());  
134        
135         print("remove age >= 24: " + users.remove(new BasicDBObject("age", new BasicDBObject("$gte", 24))).getN());  
136        
137     }  
138         
139       
140 //修改數據   
141 
142     public void modify() {  
143        
144         print("修改:" + users.update(new BasicDBObject("_id", new ObjectId("4dde25d06be7c53ffbd70906")), new BasicDBObject("age", 99)).getN());  
145        
146         print("修改:" + users.update(  
147        
148                 new BasicDBObject("_id", new ObjectId("4dde2b06feb038463ff09042")),   
149        
150                 new BasicDBObject("age", 121),  
151        
152                 true,//若是數據庫不存在,是否添加  
153        
154                 false//多條修改  
155        
156                 ).getN());  
157        
158         print("修改:" + users.update(  
159        
160                 new BasicDBObject("name", "haha"),   
161        
162                 new BasicDBObject("name", "dingding"),  
163        
164                 true,//若是數據庫不存在,是否添加  
165        
166                 true//false只修改第一天,true若是有多條就不修改  
167        
168                 ).getN());  
169         
170         //當數據庫不存在就不修改、不添加數據,當多條數據就不修改  
171        
172         //print("修改多條:" + coll.updateMulti(new BasicDBObject("_id", new ObjectId("4dde23616be7c19df07db42c")), new BasicDBObject("name", "199")));  
173        
174     }  
175 
176     public void query() {  
177        
178         //查詢全部  
179        
180         //queryAll();  
181        
182       
183         //查詢id = 4de73f7acd812d61b4626a77  
184        
185         print("find id = 4de73f7acd812d61b4626a77: " + users.find(new BasicDBObject("_id", new ObjectId("4de73f7acd812d61b4626a77"))).toArray());   
186           
187         //查詢age = 24  
188        
189         print("find age = 24: " + users.find(new BasicDBObject("age", 24)).toArray());  
190         
191         //查詢age >= 24  
192        
193         print("find age >= 24: " + users.find(new BasicDBObject("age", new BasicDBObject("$gte", 24))).toArray());  
194        
195         print("find age <= 24: " + users.find(new BasicDBObject("age", new BasicDBObject("$lte", 24))).toArray());  
196        
197            print("查詢age!=25:" + users.find(new BasicDBObject("age", new BasicDBObject("$ne", 25))).toArray());  
198        
199         print("查詢age in 25/26/27:" + users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.IN, new int[] { 25, 26, 27 }))).toArray());  
200        
201         print("查詢age not in 25/26/27:" + users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.NIN, new int[] { 25, 26, 27 }))).toArray());  
202        
203         print("查詢age exists 排序:" + users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.EXISTS, true))).toArray());  
204         
205         print("只查詢age屬性:" + users.find(null, new BasicDBObject("age", true)).toArray());  
206        
207         print("只查屬性:" + users.find(null, new BasicDBObject("age", true), 0, 2).toArray());  
208        
209         print("只查屬性:" + users.find(null, new BasicDBObject("age", true), 0, 2, Bytes.QUERYOPTION_NOTIMEOUT).toArray());  
210         
211         //只查詢一條數據,多條去第一條  
212        
213         print("findOne: " + users.findOne());  
214        
215         print("findOne: " + users.findOne(new BasicDBObject("age", 26)));  
216        
217         print("findOne: " + users.findOne(new BasicDBObject("age", 26), new BasicDBObject("name", true)));  
218         
219         //查詢修改、刪除  
220        
221         print("findAndRemove 查詢age=25的數據,而且刪除: " + users.findAndRemove(new BasicDBObject("age", 25)));  
222        
223            
224         //查詢age=26的數據,而且修改name的值爲Abc  
225        
226         print("findAndModify: " + users.findAndModify(new BasicDBObject("age", 26), new BasicDBObject("name", "Abc")));  
227        
228         print("findAndModify: " + users.findAndModify(  
229        
230             new BasicDBObject("age", 28), //查詢age=28的數據  
231        
232             new BasicDBObject("name", true), //查詢name屬性  
233        
234             new BasicDBObject("age", true), //按照age排序  
235        
236             false, //是否刪除,true表示刪除  
237        
238             new BasicDBObject("name", "Abc"), //修改的值,將name修改爲Abc  
239        
240             true,   
241        
242             true));  
243        
244            
245         queryAll();  
246        
247     }  
248     //mongoDB不支持聯合查詢、子查詢,這須要咱們本身在程序中完成。將查詢的結果集在Java查詢中進行須要的過濾便可。   
249 
250     //其餘操做   
251       
252     public void testOthers() {  
253        
254         DBObject user = new BasicDBObject();  
255        
256         user.put("name", "hoojo");  
257        
258         user.put("age", 24);  
259        
260          //JSON 對象轉換          
261        
262         print("serialize: " + JSON.serialize(user));  
263        
264         //反序列化  
265        
266         print("parse: " + JSON.parse("{ \"name\" : \"hoojo\" , \"age\" : 24}"));  
267        
268         print("判斷temp Collection是否存在: " + db.collectionExists("temp"));  
269         
270         //若是不存在就建立  
271        
272         if (!db.collectionExists("temp")) {  
273        
274             DBObject options = new BasicDBObject();  
275        
276             options.put("size", 20);  
277        
278             options.put("capped", 20);  
279        
280             options.put("max", 20);  
281        
282             print(db.createCollection("account", options));  
283        
284         }  
285        
286         //設置db爲只讀  
287        
288         db.setReadOnly(true);  
289         
290         //只讀不能寫入數據  
291        
292         db.getCollection("test").save(user);  
293        
294     }  
295 
296 }
View Code
相關文章
相關標籤/搜索