上一篇文章: http://www.cnblogs.com/hoojo/archive/2011/06/01/2066426.html介紹到了在MongoDB的控制檯完成MongoDB的數據操做,經過前一篇文章咱們對MongoDB有了全面的認識和理解。如今咱們就用Java來操做MongoDB的數據。html
開發環境:java
System:Windowsgit
IDE:eclipse、MyEclipse 8github
Database:mongoDBmongodb
開發依賴庫:數據庫
JavaEE五、mongo-2.5.3.jar、junit-4.8.2.jarapp
Email:hoojo_@126.comeclipse
Blog:http://blog.csdn.net/IBM_hoojo測試
一、 首先,下載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
二、 下面創建一個JavaProject工程,導入下載下來的驅動包。便可在Java中使用mongoDB,目錄以下:
在本示例以前你須要啓動mongod.exe的服務,啓動後,下面的程序才能順利執行;
一、 創建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());
}
完整源碼
package com.hoo.test;
import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;
/**
* <b>function:</b>MongoDB 簡單示例
* @author hoojo
* @createDate 2011-5-24 下午02:42:29
* @file SimpleTest.java
* @package com.hoo.test
* @project MongoDB
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@126.com
* @version 1.0
*/
public class SimpleTest {
public static void main(String[] args) throws UnknownHostException, MongoException {
Mongo mg = new Mongo();
//查詢全部的Database
for (String name : mg.getDatabaseNames()) {
System.out.println("dbName: " + name);
}
DB db = mg.getDB("test");
//查詢全部的彙集集合
for (String name : db.getCollectionNames()) {
System.out.println("collectionName: " + name);
}
DBCollection users = db.getCollection("users");
//查詢全部的數據
DBCursor cur = users.find();
while (cur.hasNext()) {
System.out.println(cur.next());
}
System.out.println(cur.count());
System.out.println(cur.getCursorId());
System.out.println(JSON.serialize(cur));
}
}
二、 完成CRUD操做,首先創建一個MongoDB4CRUDTest.java,基本測試代碼以下:
package com.hoo.test;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.bson.types.ObjectId;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.mongodb.BasicDBObject;
import com.mongodb.Bytes;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.QueryOperators;
import com.mongodb.util.JSON;
/**
* <b>function:</b>實現MongoDB的CRUD操做
* @author hoojo
* @createDate 2011-6-2 下午03:21:23
* @file MongoDB4CRUDTest.java
* @package com.hoo.test
* @project MongoDB
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@126.com
* @version 1.0
*/
public class MongoDB4CRUDTest {
private Mongo mg = null;
private DB db;
private DBCollection users;
@Before
public void init() {
try {
mg = new Mongo();
//mg = new Mongo("localhost", 27017);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
//獲取temp DB;若是默認沒有建立,mongodb會自動建立
db = mg.getDB("temp");
//獲取users DBCollection;若是默認沒有建立,mongodb會自動建立
users = db.getCollection("users");
}
@After
public void destory() {
if (mg != null)
mg.close();
mg = null;
db = null;
users = null;
System.gc();
}
public void print(Object o) {
System.out.println(o);
}
}
三、 添加操做
在添加操做以前,咱們須要寫個查詢方法,來查詢全部的數據。代碼以下:
/**
* <b>function:</b> 查詢全部數據
* @author hoojo
* @createDate 2011-6-2 下午03:22:40
*/
private void queryAll() {
print("查詢users的全部數據:");
//db遊標
DBCursor cur = users.find();
while (cur.hasNext()) {
print(cur.next());
}
}
@Test
public void add() {
//先查詢全部數據
queryAll();
print("count: " + users.count());
DBObject user = new BasicDBObject();
user.put("name", "hoojo");
user.put("age", 24);
//users.save(user)保存,getN()獲取影響行數
//print(users.save(user).getN());
//擴展字段,隨意添加字段,不影響現有數據
user.put("sex", "男");
print(users.save(user).getN());
//添加多條數據,傳遞Array對象
print(users.insert(user, new BasicDBObject("name", "tom")).getN());
//添加List集合
List<DBObject> list = new ArrayList<DBObject>();
list.add(user);
DBObject user2 = new BasicDBObject("name", "lucy");
user.put("age", 22);
list.add(user2);
//添加List集合
print(users.insert(list).getN());
//查詢下數據,看看是否添加成功
print("count: " + users.count());
queryAll();
}
四、 刪除數據
@Test
public void remove() {
queryAll();
print("刪除id = 4de73f7acd812d61b4626a77:" + users.remove(new BasicDBObject("_id", new ObjectId("4de73f7acd812d61b4626a77"))).getN());
print("remove age >= 24: " + users.remove(new BasicDBObject("age", new BasicDBObject("$gte", 24))).getN());
}
五、 修改數據
@Test
public void modify() {
print("修改:" + users.update(new BasicDBObject("_id", new ObjectId("4dde25d06be7c53ffbd70906")), new BasicDBObject("age", 99)).getN());
print("修改:" + users.update(
new BasicDBObject("_id", new ObjectId("4dde2b06feb038463ff09042")),
new BasicDBObject("age", 121),
true,//若是數據庫不存在,是否添加
false//多條修改
).getN());
print("修改:" + users.update(
new BasicDBObject("name", "haha"),
new BasicDBObject("name", "dingding"),
true,//若是數據庫不存在,是否添加
true//false只修改第一天,true若是有多條就不修改
).getN());
//當數據庫不存在就不修改、不添加數據,當多條數據就不修改
//print("修改多條:" + coll.updateMulti(new BasicDBObject("_id", new ObjectId("4dde23616be7c19df07db42c")), new BasicDBObject("name", "199")));
}
六、 查詢數據
@Test
public void query() {
//查詢全部
//queryAll();
//查詢id = 4de73f7acd812d61b4626a77
print("find id = 4de73f7acd812d61b4626a77: " + users.find(new BasicDBObject("_id", new ObjectId("4de73f7acd812d61b4626a77"))).toArray());
//查詢age = 24
print("find age = 24: " + users.find(new BasicDBObject("age", 24)).toArray());
//查詢age >= 24
print("find age >= 24: " + users.find(new BasicDBObject("age", new BasicDBObject("$gte", 24))).toArray());
print("find age <= 24: " + users.find(new BasicDBObject("age", new BasicDBObject("$lte", 24))).toArray());
print("查詢age!=25:" + users.find(new BasicDBObject("age", new BasicDBObject("$ne", 25))).toArray());
print("查詢age in 25/26/27:" + users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.IN, new int[] { 25, 26, 27 }))).toArray());
print("查詢age not in 25/26/27:" + users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.NIN, new int[] { 25, 26, 27 }))).toArray());
print("查詢age exists 排序:" + users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.EXISTS, true))).toArray());
print("只查詢age屬性:" + users.find(null, new BasicDBObject("age", true)).toArray());
print("只查屬性:" + users.find(null, new BasicDBObject("age", true), 0, 2).toArray());
print("只查屬性:" + users.find(null, new BasicDBObject("age", true), 0, 2, Bytes.QUERYOPTION_NOTIMEOUT).toArray());
//只查詢一條數據,多條去第一條
print("findOne: " + users.findOne());
print("findOne: " + users.findOne(new BasicDBObject("age", 26)));
print("findOne: " + users.findOne(new BasicDBObject("age", 26), new BasicDBObject("name", true)));
//查詢修改、刪除
print("findAndRemove 查詢age=25的數據,而且刪除: " + users.findAndRemove(new BasicDBObject("age", 25)));
//查詢age=26的數據,而且修改name的值爲Abc
print("findAndModify: " + users.findAndModify(new BasicDBObject("age", 26), new BasicDBObject("name", "Abc")));
print("findAndModify: " + users.findAndModify(
new BasicDBObject("age", 28), //查詢age=28的數據
new BasicDBObject("name", true), //查詢name屬性
new BasicDBObject("age", true), //按照age排序
false, //是否刪除,true表示刪除
new BasicDBObject("name", "Abc"), //修改的值,將name修改爲Abc
true,
true));
queryAll();
}
mongoDB不支持聯合查詢、子查詢,這須要咱們本身在程序中完成。將查詢的結果集在Java查詢中進行須要的過濾便可。
七、 其餘操做
public void testOthers() {
DBObject user = new BasicDBObject();
user.put("name", "hoojo");
user.put("age", 24);
//JSON 對象轉換
print("serialize: " + JSON.serialize(user));
//反序列化
print("parse: " + JSON.parse("{ \"name\" : \"hoojo\" , \"age\" : 24}"));
print("判斷temp Collection是否存在: " + db.collectionExists("temp"));
//若是不存在就建立
if (!db.collectionExists("temp")) {
DBObject options = new BasicDBObject();
options.put("size", 20);
options.put("capped", 20);
options.put("max", 20);
print(db.createCollection("account", options));
}
//設置db爲只讀
db.setReadOnly(true);
//只讀不能寫入數據
db.getCollection("test").save(user);
}
好了,這裏基本上就介紹這麼多Java操做MongoDB的方法。其餘的東西還須要你本身多多研究。上面操做MongoDB的方法都是一些經常使用的方法,比較簡單。若是有什麼問題,能夠給我留言或是發Email:hoojo_@126.com