驅動包下載:https://github.com/mongodb/mongo-java-driver/downloads
我下載的是 mongo-2.8.0.jar —
Version 2.8.0
開啟mongo shell -- 建立資料庫test --( use test)
開啟eclipse建立工程,把junit,mongo-2.8.0.jar匯入。
建立測試類別如下:
package com.db;import java.net.UnknownHostException;import java.util.ArrayList;import java.util.List;import org.bson.types.ObjectId;import org.junit.After;import org.junit.Test;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 DBUtils { private static Mongo mongo; private static DB db; static { try { mongo = new Mongo("localhost", 27017); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } db = mongo.getDB("test"); } @After public void output() { // 測試完顯示所有 DBCollection dbc = db.getCollection("user"); DBCursor cursor = dbc.find(); while (cursor.hasNext()) { // cursor.next就是一行記錄(一個文檔) System.out.println(cursor.next()); } } @Test public void testInsert() throws Exception { DBCollection dbc = db.getCollection("user"); DBObject object = new BasicDBObject(); object.put("username", "zdw"); object.put("password", "123"); // 一個人有一個職位 // 資料庫json格式:{username:"zdw",password:"123",position:{name:"工程師"}} BasicDBObject o = new BasicDBObject(); o.put("name", "經理"); object.put("position", o); dbc.insert(object); object = new BasicDBObject(); object.put("username", "zhangjun"); object.put("password", "456"); // 一個人有多個職位(一個文檔裡有多個文檔) // 資料庫json格式:{username:"zhangjun",password:"456",position:[{name:"工程師"},{name:"設計師"}]} List<Object> list = new ArrayList<Object>(); o = new BasicDBObject(); o.put("name", "工程師"); list.add(o); o = new BasicDBObject(); o.put("name", "設計師"); list.add(o); object.put("position", list); dbc.insert(object); } // 刪除指定 @Test public void testRemoveOne() throws Exception { DBCollection dbc = db.getCollection("user"); DBObject o = new BasicDBObject(); o.put("username", "zhangjun"); dbc.remove(o); } @Test public void testModify() throws Exception { DBCollection dbc = db.getCollection("user"); // 根據id修改密碼,需要加$set,否則所有記錄的password都會被修改,其它欄位刪除。 int result = dbc.update( new BasicDBObject("_id", new ObjectId( "4ff8eaa65dbc67340278a07c")), new BasicDBObject("$set", new BasicDBObject("password", "4444"))).getN(); System.out.println(result); } @Test public void testRemove() throws Exception { DBCollection dbc = db.getCollection("user"); // 刪除全部 dbc.drop(); } // 查詢指定 @Test public void testFindOne() throws Exception { DBCollection dbc = db.getCollection("user"); DBObject o = new BasicDBObject(); o.put("username", "zdw"); DBObject obj = dbc.findOne(o); System.out.println(obj); }}
這種key-value儲存方式,操作很方便。
源碼下載