Java操作MongoDB

一、准备工作

1、 首先,下载mongoDB对Java支持的驱动包 

驱动包下载地址:https://github.com/mongodb/mongo-java-driver/downloads

mongoDB对Java的相关支持、技术:http://www.mongodb.org/display/DOCS/Java+Language+Center

驱动源码下载:https://download.github.com/mongodb-mongo-java-driver-r2.6.1-7-g6037357.zip

在线查看源码:https://github.com/mongodb/mongo-java-driver

2、 下面建立一个JavaProject工程,导入下载下来的驱动包。即可在Java中使用mongoDB,目录如下: 

clip_image002

 

二、Java操作MongoDB示例

在本示例之前你需要启动mongod.exe的服务,启动后,下面的程序才能顺利执行; 

 

1、 建立SimpleTest.java,完成简单的mongoDB数据库操作 

Mongo mongo = new Mongo(); 

这样就创建了一个MongoDB的数据库连接对象,它默认连接到当前机器的localhost地址,端口是27017。 

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

 

2、 完成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

 

posted @ 2015-01-05 10:34  tbyang  阅读(500)  评论(0编辑  收藏  举报