1. 程式人生 > >MongoDB學習筆記(三) java中如何操作MongoDB

MongoDB學習筆記(三) java中如何操作MongoDB

1. mongoDB對Java支援的驅動包

驅動包下載地址:http://repo1.maven.org/maven2/org/mongodb/mongo-java-driver/
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

maven配置:

   <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>2.11.1</version>
    </dependency>

2. Java操作MongoDB示例

(1) 簡單的mongoDB資料庫操作

public class SimpleTest {

    public static void main(final String[] args) throws UnknownHostException {
        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));
    }
}

(2) CRUD操作
public class CRUDTest {

    private Mongo mg = null;
    private DB db;
    private DBCollection users;

    public static void main(String[] args) {
        CRUDTest tobj = new CRUDTest();
        tobj.init();

        tobj.add();
        // tobj.query();
        // tobj.modify();
        // tobj.remove();
        // tobj.testOthers();

        tobj.destory();
    }

    private void init() {
        try {
            mg = new Mongo();
            // mg = new Mongo("localhost", 27017);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (MongoException e) {
            e.printStackTrace();
        }

        // 獲取test DB;如果預設沒有建立,mongodb會自動建立
        db = mg.getDB("test");

        // 獲取users DBCollection;如果預設沒有建立,mongodb會自動建立
        users = db.getCollection("users");
    }

    private void destory() {
        if (mg != null) {
            mg.close();
        }

        mg = null;
        db = null;
        users = null;
        System.gc();
    }

    public void print(Object o) {
        System.out.println(o);
    }

    /**
     * 查詢所有資料
     */
    private void queryAll() {
        print("查詢users的所有資料:");

        DBCursor cur = users.find();
        while (cur.hasNext()) {
            print(cur.next());
        }
    }

    /**
     * 新增操作
     */
    public void add() {
        // 查詢資料
        queryAll();
        print("count: " + users.count());

        DBObject user = new BasicDBObject();
        user.put("name", "lilei");
        user.put("age", 20);
        user.put("sex", "male");
        // users.save(user)儲存,getN()獲取影響行數
        print(users.save(user).getN());

        // 新增多條資料,傳遞Array物件
        DBObject user2 = new BasicDBObject("name", "hanmeimei");
        user2.put("age", 18);
        print(users.insert(user2, new BasicDBObject("name", "jim")).getN());

        // 新增多條資料,傳遞List集合
        List<DBObject> list = new ArrayList<DBObject>();
        DBObject user3 = new BasicDBObject("name", "lucy");
        user3.put("age", 22);
        list.add(user3);

        DBObject user4 = new BasicDBObject("name", "tom");
        user4.put("age", 22);
        list.add(user4);

        print(users.insert(list).getN());

        // 查詢資料
        print("count: " + users.count());
        queryAll();
    }

    public void query() {
        // 查詢id
        print("查詢 id = 54f511b4e4b0ded60d95c333: "
                + users.find(new BasicDBObject("_id", new ObjectId("54f511b4e4b0ded60d95c333"))).toArray());

        // 查詢age
        print("查詢 age = 24: " + users.find(new BasicDBObject("age", 24)).toArray());
        print("查詢 age >= 24: " + users.find(new BasicDBObject("age", new BasicDBObject("$gte", 24))).toArray());
        print("查詢 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();
    }

    /**
     * 修改操作
     */
    public void modify() {
        print("修改:" + users.update(new BasicDBObject("name", "hanmeimei"), new BasicDBObject("age", 25)).getN());

        print("修改:"
                + users.update(new BasicDBObject("age", new BasicDBObject("$gte", 22)), new BasicDBObject("age", 121),
                        true,// 如果資料庫不存在,是否新增
                        false// false只修改第一條,true如果有多條就不修改
                ).getN());
    }

    /**
     * 刪除操作
     */
    public void remove() {
        print("刪除id = 54f511b4e4b0ded60d95c333:"
                + users.remove(new BasicDBObject("_id", new ObjectId("54f511b4e4b0ded60d95c333"))).getN());

        print("remove age >= 22: " + users.remove(new BasicDBObject("age", new BasicDBObject("$gte", 22))).getN());
    }

    /**
     * 其他操作
     */
    public void testOthers() {
        DBObject user = new BasicDBObject();
        user.put("name", "demo");
        user.put("age", 24);

        // JSON 物件轉換
        print("serialize: " + JSON.serialize(user));
        // 反序列化
        print("parse: " + JSON.parse("{ \"name\" : \"demo\" , \"age\" : 24}"));

        // 如果不存在就建立
        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);
    }
}