Java 操作mongodb

package cn.test.db;

import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
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.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import com.mongodb.util.JSON;

/**
 * 需引入jar包 :地址https://github.com/mongodb/mongo-java-driver/downloads
 * 根据服务器所安装版本下载对应即可>>>
 * 
 *查看版本方式:[root@vmu010226-node1 ~]# mongo version
 */

public class App {

    /**
     * 连接库 test
     * 
     * @return
     * @throws UnknownHostException
     * @throws MongoException
     */
    public static DB getDb() throws UnknownHostException, MongoException {
        // 实例化Mongo对象,连接27017端口
        Mongo mongo = new Mongo("10.1.207.110", 27017);
        // 连接名为test的数据库,假如数据库不存在的话,mongodb会自动建立
        DB db = mongo.getDB("test");
        return db;
    }

    /**
     * 获取所有的集合名
     * 
     * @throws MongoException
     * @throws UnknownHostException
     */
    public void getCollectionName() throws MongoException, UnknownHostException {
        Set<String> collections = getDb().getCollectionNames();
        for (String collectionName : collections) {
            System.out.println("collectionName=" + collectionName);
        }
    }

    /**
     * 与集合名为game的取得连接
     * 
     * @return
     * @throws UnknownHostException
     * @throws MongoException
     */
    public static DBCollection getCollection() throws UnknownHostException,
            MongoException {
        DBCollection collection = getDb().getCollection("game");
        return collection;
    }

    /**
     * insert 第一种方法,是使用BasicDBObjec
     * 
     * @throws MongoException
     * @throws UnknownHostException
     */
    public static void insertByBasicDBObject() throws MongoException,
            UnknownHostException {
        BasicDBObject document = new BasicDBObject();
        document.put("id", 1);
        document.put("name", "测试数据no1");
        document.put("content", "评价no1");
        document.put("score", 5000);
        BasicDBObject documentDetail = new BasicDBObject();
        documentDetail.put("records", "99");
        documentDetail.put("index", "vps_index1");
        documentDetail.put("active", "true");
        document.put("detail", documentDetail);
        getCollection().insert(document);
        /***
         * 输出结果 :{ "_id" : ObjectId("547536e291812694b70f5059"), "id" : 1,
         * "name" : "测试数据no1", "content" : "评价no1", "score" : 5000, "detail" : {
         * "records" : "99", "index" : "vps_index1", "active" : "true" } }
         */
    }

    /**
     * insert 第二种方法,是使用BasicDBObjectBuilder
     * 
     * @throws MongoException
     * @throws UnknownHostException
     */
    public static void insertByBasicDBObjectBuilder() throws MongoException,
            UnknownHostException {
        BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
                .add("id", 2).add("name", "测试数据no2").add("content", "评价no2")
                .add("score", 5000);
        BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder
                .start().add("records", "100").add("index", "vps_index2").add(
                        "active", "true");
        documentBuilder.add("detail", documentBuilderDetail.get());
        getCollection().insert(documentBuilder.get());
        /***
         * 输出结果 :{ "_id" : ObjectId("547539009181903d3a37ddeb"), "id" : 2,
         * "name" : "测试数据no2", "content" : "评价no2", "score" : 5000, "detail" : {
         * "records" : "100", "index" : "vps_index2", "active" : "true" } }
         */
    }

    /**
     * insert 第三种方法,是使用Map
     * 
     * @throws MongoException
     * @throws UnknownHostException
     */
    @SuppressWarnings("unchecked")
    public static void insertByMap() throws MongoException,
            UnknownHostException {
        Map documentMap = new HashMap();
        documentMap.put("id", 3);
        documentMap.put("name", "测试数据no3");
        documentMap.put("content", "评价no3");
        documentMap.put("score", 5000);
        Map documentMapDetail = new HashMap();
        documentMapDetail.put("records", "99");
        documentMapDetail.put("index", "vps_index3");
        documentMapDetail.put("active", "true");
        documentMap.put("detail", documentMapDetail);
        getCollection().insert(new BasicDBObject(documentMap));
        /**
         * 输出结果:{ "_id" : ObjectId("547539ff9181629953cc678c"), "content" :
         * "评价no3", "id" : 3, "detail" : { "index" : "vps_index3", "active" :
         * "true", "records" : "99" }, "name" : "测试数据no3", "score" : 5000 }
         */
    }

    /**
     * insert 第四种方法,直接使用json格式
     * 
     * @throws MongoException
     * @throws UnknownHostException
     */
    public static void insertByJson() throws MongoException,
            UnknownHostException {
        String json = "{'database' : 'mkyongDB','table' : 'hosting',"
                + "'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}";
        DBObject dbObject = (DBObject) JSON.parse(json);
        getCollection().insert(dbObject);
        /**
         * 输出结果:{ "_id" : ObjectId("54753abd91810ba1daa7ff0f"), "database" :
         * "mkyongDB", "table" : "hosting", "detail" : { "records" : 99, "index"
         * : "vps_index1", "active" : "true" } }
         */
    }

    /****
     * 
     * game集合里面现在的数据为 > db.game.find() { "_id" :
     * ObjectId("547443c4c9158f23e626927f"), "name" : "my hero", "content" :
     * "are you sure?", "score" : 20000 } { "_id" :
     * ObjectId("54752f5f9181f945548b2375"), "id" : 1001, "name" : "啦啦啦啦啦啦啦",
     * "content" : "hello world mongoDB in Java", "score" : 1 } { "_id" :
     * ObjectId("547530ac9181d6f709a151f0"), "id" : 1001, "name" : "啦啦啦啦啦啦啦",
     * "content" : "hello world mongoDB in Java", "score" : 1 } { "_id" :
     * ObjectId("547536e291812694b70f5059"), "id" : 1, "name" : "测试数据no1",
     * "content" : "评价no1", "score" : 5000, "detail" : { "records" : "99",
     * "index" : "vps_index1", "active" : "true" } } { "_id" :
     * ObjectId("547539009181903d3a37ddeb"), "id" : 2, "name" : "测试数据no2",
     * "content" : "评价no2", "score" : 5000, "detail" : { "records" : "100",
     * "index" : "vps_index2", "active" : "true" } } { "_id" :
     * ObjectId("547539ff9181629953cc678c"), "content" : "评价no3", "id" : 3,
     * "detail" : { "index" : "vps_index3", "active" : "true", "records" : "99"
     * }, "name" : "测试数据no3", "score" : 5000 } { "_id" :
     * ObjectId("54753abd91810ba1daa7ff0f"), "database" : "mkyongDB", "table" :
     * "hosting", "detail" : { "records" : 99, "index" : "vps_index1", "active"
     * : "true" } }
     * 
     */
    // 更新 .............

    /**
     * update
     * 
     * @param args
     * @throws UnknownHostException
     * @throws MongoException
     *              使用BasicDBObject对象,并为其赋值了新的值后,然后使用collection的update方法,即可更新该对象
     */
    public static void update_1() throws MongoException, UnknownHostException {
        // ** 将这条数据更新 { "_id" : ObjectId("547443c4c9158f23e626927f"), "name" :
        // "my hero", "content" : "are you sure?", "score" : 20000 }
        BasicDBObject newDocument = new BasicDBObject();
        newDocument.put("name", "my new hero");
        newDocument.put("content", "这是我的新英雄!");
        newDocument.put("score", 15400);
        getCollection().update(new BasicDBObject().append("name", "my hero"),
                newDocument);
        /**
         * 输出结果 :{ "_id" : ObjectId("547443c4c9158f23e626927f"), "name" :
         * "my new hero", "content" : "这是我的新英雄!", "score" : 15400 }
         */
    }

    /***
     * 
     * 还可以使用mongodb中的$inc修饰符号去对某个值进行更新,比如,要将name值为my new
     * hero的document的score的值得更新为16000(即15400+4600=16000)
     * 
     * @param args
     * @about "$inc"更新修改器 可作为计数器
     */
    public static void update_inc() throws MongoException, UnknownHostException {
        /**
         * 初始{ "_id" : ObjectId("547443c4c9158f23e626927f"), "name" :
         * "my new hero", "content" : "这是我的新英雄!", "score" : 15400 }
         */
        BasicDBObject newDocument = new BasicDBObject().append("$inc",
                new BasicDBObject().append("score", 4600));
        getCollection().update(
                new BasicDBObject().append("name", "my new hero"), newDocument);
        /**
         * 输出结果 :{ "_id" : ObjectId("547443c4c9158f23e626927f"), "name" :
         * "my new hero", "content" : "这是我的新英雄!", "score" : 20000 }
         */
    }

    /**
     * "$set" 可添加字段内容
     * 
     * @throws MongoException
     * @throws UnknownHostException
     */
    public static void update_set() throws MongoException, UnknownHostException {
        BasicDBObject newDocument = new BasicDBObject().append("$set",
                new BasicDBObject().append("useset", "使用$set"));
        getCollection().update(
                new BasicDBObject().append("name", "my new hero"), newDocument);
        /**
         * 输出结果 :{ "_id" : ObjectId("547443c4c9158f23e626927f"), "name" :
         * "my new hero", "content" : "这是我的新英雄!", "score" : 20000, "useset" :
         * "使用$set" }
         */
    }

    /**
     * "$unset" 可删除字段内容
     * 
     * @throws MongoException
     * @throws UnknownHostException
     */
    public static void update_unset() throws MongoException,
            UnknownHostException {
        BasicDBObject newDocument = new BasicDBObject().append("$unset",
                new BasicDBObject().append("useset", "使用$set"));
        getCollection().update(
                new BasicDBObject().append("name", "my new hero"), newDocument);
        /**
         * 输出结果 :{ "_id" : ObjectId("547443c4c9158f23e626927f"), "name" :
         * "my new hero", "content" : "这是我的新英雄!", "score" : 20000 }
         */
    }

    /**
     * 批量更新
     * 
     * @throws MongoException
     * @throws UnknownHostException
     */
    public static void update_multi() throws MongoException,
            UnknownHostException {
        // 将id为1001的数据的score更新为999999
        /**
         * 初始值:{ "_id" : ObjectId("54752f5f9181f945548b2375"), "id" : 1001,
         * "name" : "啦啦啦啦啦啦啦", "content" : "hello world mongoDB in Java",
         * "score" : 1 } { "_id" : ObjectId("547530ac9181d6f709a151f0"), "id" :
         * 1001, "name" : "啦啦啦啦啦啦啦", "content" : "hello world mongoDB in Java",
         * "score" : 1 }
         */
        BasicDBObject updateQuery = new BasicDBObject().append("$set",
                new BasicDBObject().append("score", 999999));
        getCollection().update(new BasicDBObject().append("id", 1001),
                updateQuery, false, true);
        /**
         * 输出结果 { "_id" : ObjectId("54752f5f9181f945548b2375"), "id" : 1001,
         * "name" : "啦啦啦啦啦啦啦", "content" : "hello world mongoDB in Java",
         * "score" : 999999 } { "_id" : ObjectId("547530ac9181d6f709a151f0"),
         * "id" : 1001, "name" : "啦啦啦啦啦啦啦", "content" :
         * "hello world mongoDB in Java", "score" : 999999 }
         */
    }

    // 查询

    /**
     * 查询Document
     * 
     * 先用下面的代码往数据库中插入1-10数字:
     */

    public static void init() throws MongoException, UnknownHostException {

        for (int i = 1; i <= 10; i++) {
            getCollection().insert(new BasicDBObject().append("number", i));
        }
        /**
         * 结果为: { "_id" : ObjectId("547562c991818dbe4d036486"), "number" : 1 } {
         * "_id" : ObjectId("547562c991818dbe4d036487"), "number" : 2 } { "_id"
         * : ObjectId("547562c991818dbe4d036488"), "number" : 3 } { "_id" :
         * ObjectId("547562c991818dbe4d036489"), "number" : 4 } { "_id" :
         * ObjectId("547562c991818dbe4d03648a"), "number" : 5 } { "_id" :
         * ObjectId("547562c991818dbe4d03648b"), "number" : 6 } { "_id" :
         * ObjectId("547562c991818dbe4d03648c"), "number" : 7 } { "_id" :
         * ObjectId("547562c991818dbe4d03648d"), "number" : 8 } { "_id" :
         * ObjectId("547562c991818dbe4d03648e"), "number" : 9 } { "_id" :
         * ObjectId("547562c991818dbe4d03648f"), "number" : 10 }
         */
    }

    /**
     * 查询第一个数据
     * 
     * @throws MongoException
     * @throws UnknownHostException
     */
    public static void findOne() throws MongoException, UnknownHostException {
        DBObject dbObject = getCollection().findOne(); // 等同于mongo 执行
        // db.game.findOne()
        System.out.println(dbObject);
        /**
         * 输出结果 :{ "_id" : ObjectId("547562c991818dbe4d036486"), "number" : 1 }
         */

    }

    /**
     * 获得document的集合
     * 
     * @param
     * @throws MongoException
     * @throws UnknownHostException
     */

    public static void getDocCollections() throws UnknownHostException,
            MongoException {
        DBCursor cursor = getCollection().find();
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
        /***
         * 输出结果为:{ "_id" : { "$oid" : "547562c991818dbe4d036486"} , "number" :
         * 1} { "_id" : { "$oid" : "547562c991818dbe4d036487"} , "number" : 2} {
         * "_id" : { "$oid" : "547562c991818dbe4d036488"} , "number" : 3} {
         * "_id" : { "$oid" : "547562c991818dbe4d036489"} , "number" : 4} {
         * "_id" : { "$oid" : "547562c991818dbe4d03648a"} , "number" : 5} {
         * "_id" : { "$oid" : "547562c991818dbe4d03648b"} , "number" : 6} {
         * "_id" : { "$oid" : "547562c991818dbe4d03648c"} , "number" : 7} {
         * "_id" : { "$oid" : "547562c991818dbe4d03648d"} , "number" : 8} {
         * "_id" : { "$oid" : "547562c991818dbe4d03648e"} , "number" : 9} {
         * "_id" : { "$oid" : "547562c991818dbe4d03648f"} , "number" : 10}
         */
    }

    /**
     * 获得document集合的总数
     * 
     * @throws UnknownHostException
     * @throws MongoException
     */
    public static void getDocCount() throws UnknownHostException,
            MongoException {
        DBCursor cursor = getCollection().find();
        System.out.println(cursor.count());
    }

    /**
     * 根据条件取document
     * 
     * @throws UnknownHostException
     * @throws MongoException
     */
    @SuppressWarnings("unchecked")
    public static void getDocCollectionsByCondition()
            throws UnknownHostException, MongoException {
        BasicDBObject query = new BasicDBObject();
        query.put("number", 5); // 取number 为5的document
        DBCursor cursor = getCollection().find(query);
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }// 输出结果:{ "_id" : { "$oid" : "547562c991818dbe4d03648a"} , "number" :
        // 5}
        /**
         * 使用 "$in"
         */
        BasicDBObject query_in = new BasicDBObject();
        List list_in = new ArrayList();
        list_in.add(9);
        list_in.add(10);
        query_in.put("number", new BasicDBObject("$in", list_in)); // 取number等于9和10的数据
        DBCursor cursor_in = getCollection().find(query_in);
        while (cursor_in.hasNext()) {
            System.out.println(cursor_in.next());// 输出结果:{ "_id" : { "$oid" :
            // "547562c991818dbe4d03648e"}
            // , "number" : 9}
            // { "_id" : { "$oid" : "547562c991818dbe4d03648f"} , "number" : 10}
        }
        /*
         * 使用>,<等比较符号 "$lt" "$lte" "$gt" "$gte" "$ne" //小于 小于等于 大于 大于等于 不等于
         */
        BasicDBObject query_gt = new BasicDBObject();
        query_gt.put("number", new BasicDBObject("$gt", 5).append("$lte", 8)); // 大于5小于8
        DBCursor cursor_gt = getCollection().find(query_gt);
        while (cursor_gt.hasNext()) {
            System.out.println(cursor_gt.next());// 输出结果:{ "_id" : { "$oid" :
            // "547562c991818dbe4d03648b"}
            // , "number" : 6}
            // { "_id" : { "$oid" : "547562c991818dbe4d03648c"} , "number" : 7}
            // { "_id" : { "$oid" : "547562c991818dbe4d03648d"} , "number" : 8}
        }

    }

    /**
     * 删除操作
     */
    @SuppressWarnings("unchecked")
    public static void removeFirstOne() throws MongoException,
            UnknownHostException {
        // 删除第一个document
        DBObject dbObject = getCollection().findOne();
        getCollection().remove(dbObject);

        // 删除指定的document
        BasicDBObject document = new BasicDBObject();
        document.put("number", 2);
        getCollection().remove(document);

        // 使用$in 删除多个document
        BasicDBObject query_in = new BasicDBObject();
        List list_in = new ArrayList();
        list_in.add(9);
        list_in.add(10);
        query_in.put("number", new BasicDBObject("$in", list_in)); // 先取number等于9和10的数据
        getCollection().remove(query_in);

        // 删除所有的document
        DBCursor cursor = getCollection().find();
        while (cursor.hasNext()) {
            getCollection().remove(cursor.next());
        }
    }

    /**
     * 保存图片
     * 
     * @throws IOException
     */
    public static void savePhoto() throws IOException {
        String newFileName = "test-mongo-image";
        File imageFile = new File("C:\\Users\\xiao\\Desktop\\pda\\logo.gif");
        GridFS gfsPhoto = new GridFS(getDb(), "photo");
        GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
        gfsFile.setFilename(newFileName);
        gfsFile.save();
    }

    /**
     * 读取图片
     * 
     * @throws UnknownHostException
     * @throws MongoException
     */
    public static void readPhoto() throws UnknownHostException, MongoException {
        String newFileName = "test-mongo-image";
        GridFS gfsPhoto = new GridFS(getDb(), "photo");
        GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
        System.out.println(imageForOutput);
        /**
         * 
         * 
         *输出结果:{ "_id" : { "$oid" : "54756e479181e6adf838e1f0"} , "chunkSize" :
         * 262144 , "length" : 5238 , "md5" : "a47baf8201db57a790c91c88329aaa69"
         * , "filename" : "test-mongo-image" , "contentType" : null ,
         * "uploadDate" : { "$date" : "2014-11-26T06:08:07.047Z"} , "aliases" :
         * null }
         * 
         * 
         */
    }

    /**
     * 读取所有的图片
     * 
     * @throws UnknownHostException
     * @throws MongoException
     */
    public static void readAllPhoto() throws UnknownHostException,
            MongoException {
        GridFS gfsPhoto = new GridFS(getDb(), "photo");
        DBCursor cursor = gfsPhoto.getFileList();
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    }

    /**
     * 从数据库读取后写入到磁盘上
     * 
     * @throws IOException
     */
    public static void readToWrite() throws IOException {
        String newFileName = "test-mongo-image";
        GridFS gfsPhoto = new GridFS(getDb(), "photo");
        GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
        imageForOutput.writeTo("c:\\JavaWebHostingNew.png");
    }

    /**
     * 删除图片
     * 
     * @throws UnknownHostException
     * @throws MongoException
     */
    public static void removePhotos() throws UnknownHostException,
            MongoException {
        String newFileName = "test-mongo-image";
        GridFS gfsPhoto = new GridFS(getDb(), "photo");
        gfsPhoto.remove(gfsPhoto.findOne(newFileName));
    }

    public static void main(String[] args) throws Exception {
        /**
         * 插入 4种方式
         */
        // insertByBasicDBObject();
        // insertByBasicDBObjectBuilder();
        // insertByMap();
        // insertByJson();
        /**
         * 更新
         * */
        // update_1();
        // update_inc();
        // update_set();
        // update_unset();
        // update_multi();
        /**
         * 初始化需要查询的数据
         */
        // init();
        // findOne();
        // getDocCollections();
        // getDocCount();
        // getDocCollectionsByCondition();
        // removeFirstOne();

        /**
         * 图片操作
         */
        // savePhoto();
        // readPhoto();
        // readAllPhoto();
        // readToWrite();
        // removePhotos();
        System.out.println("done....");

    }
}

源码地址:http://download.csdn.net/detail/u010497606/8200295

 

 

posted @ 2014-11-26 14:41  justin_xiaoshuai  阅读(283)  评论(0编辑  收藏  举报