Java MongoDB插入


前言

        插入是向MongoDB中添加數據的基本方法。對目標集使用insert方法來插入一條文檔。這個方法會給文檔增加一個”_id”屬性(如果原來沒有的話),然后保存到數據庫中。

 

1、連接數據庫,拿到集合firstCollection

 

        MongoClient mClient = new MongoClient("10.211.55.8");

        DB db = mClient.getDB("test");

        DBCollection collection = db.getCollection("firstCollection");

2、插入一條文檔

        內容:name:user28,age:30,sex:1

 

        Java方法內容:

        BasicDBObject obj = new BasicDBObject();

        obj.put("name", "user28");

        obj.put("age", 30);

        obj.put("sex", 1);

        collection.insert(obj);

        這樣就成功插入了一條文檔,插入后的內容如下所示:

        { "_id" : ObjectId("55bf285368084e1906793d7a"), "name" : "user28", "age" : 30, "sex" : 1 }

3、批量插入文檔

        當需要插入多條文檔的時候,循環進行單條插入當然是可以,但是效率不高,MongoDB提供了批量插入的方法

        內容1:name:user29,age:30,sex:1

        內容2:name:user30,age:30,sex:1

 

        Java方法內容:

        List<DBObject> objs = new ArrayList<DBObject>();

        objs.add(new BasicDBObject("name","user29").append("age", 30).append("sex", 1));

        objs.add(new BasicDBObject("name","user30").append("age", 30).append("sex", 1));

        collection.insert(objs);

 

        這樣就批量進行了插入。批量插入通過一次請求將數據傳遞給數據庫,然后由數據庫進行插入,比循環單條插入節省了每次進行請求的資源。

4、利用update方法插入

        一般update用於更新文檔,但是這個方法的upsert屬性可以使得在沒有查找到要更新的文檔的時候插入一條新文檔

 

        public WriteResult update(DBObject query,

                                                DBObject update,

                                                boolean upsert,

                                                boolean multi)

        參數介紹:

                query - the selection criteria for the update

                update - the modifications to apply

                upsert - when true, inserts a document if no document matches the update query criteria

                multi - when true, updates all documents in the collection that match the update query criteria, otherwise only updates one

        Java方法內容:

        collection.update(new BasicDBObject("name","user31"),

                new BasicDBObject("name","user31").append("sex", 1).append("age", 30)

                ,true,false);

5、通過save方法來插入

        MongoDB中save也有插入的功能,但是和insert相比有些區別

        1、save相當於根據不同條件去執行insert或者update功能(這個條件就是_id屬性),而insert只有插入功能

        2、save只能單條記錄,如果有數組,需要遍歷進行處理,而insert可以直接處理數組,所以在處理批量插入的時候insert效率會高很多

 

        利用save方法插入文檔,java方法內容:

        BasicDBObject obj = new BasicDBObject("name","user30").append("age", 30);

        collection.save(obj);

                

6、插入原理

        當執行出入的時候,使用的驅動程序會將數據轉換成BSON 的形式,然后送入數據庫。數據庫解析BSON內容,檢查是否存在_id屬性,如果沒有則給予生成一個。然后就原樣的將數據存入數據庫中。由於MongoDB在插入數據的時候不執行代碼,所以在這部分就杜絕了注入式攻擊的可能

 

7、總結

        插入文檔有很多方式,但是在不同的條件下不同的方法有着不同的執行效率,所以需要根據實際的業務場景選擇合適的方法

備注

        文中節選了《MongoDB權威指南》的部分內容。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM