SpringBoot高級篇MongoDB之如何新增文檔

本篇博文爲mongodb的curd中一篇,前面介紹簡單的查詢使用,這一篇重點則放在插入數據;java

I. 基本使用

首先是準備好基本環境,能夠參考博文mysql

1. 新增一條數據

MongoDB一個基本數據稱爲document,和mysql不同,沒有強制約束哪些字段,能夠隨意的插入,下面是一個簡單的插入演示git

private static final String COLLECTION_NAME = "demo";

@Autowired
private MongoTemplate mongoTemplate;

/** * 新增一條記錄 */
public void insert() {
    JSONObject object = new JSONObject();
    object.put("name", "一灰灰blog");
    object.put("desc", "歡迎關注一灰灰Blog");
    object.put("age", 28);

    // 插入一條document
    mongoTemplate.insert(object, COLLECTION_NAME);


    JSONObject ans = mongoTemplate
            .findOne(new Query(Criteria.where("name").is("一灰灰blog").and("age").is(28)), JSONObject.class,
                    COLLECTION_NAME);
    System.out.println(ans);
}
複製代碼

使用的關鍵地方爲一行: mongoTemplate.insert(object, COLLECTION_NAME);github

  • 第一個參數爲待插入的document
  • 第二個參數爲collection name (至關於mysql的table)

執行後輸出結果爲以下spring

{"name":"一灰灰blog","_id":{"counter":12472353,"date":1548333180000,"machineIdentifier":14006254,"processIdentifier":17244,"time":1548333180000,"timeSecond":1548333180,"timestamp":1548333180},"age":28,"desc":"歡迎關注一灰灰Blog"}
複製代碼

2. 批量插入

一次插入多條記錄,傳集合進去便可sql

/** * 批量插入 */
public void insertMany() {
    List<Map<String, Object>> records = new ArrayList<>();
    for (int i = 0; i < 3; i++) {
        Map<String, Object> record = new HashMap<>(4);
        record.put("wechart", "一灰灰blog");
        record.put("blog", Arrays.asList("http://spring.hhui.top", "http://blog.hhui.top"));
        record.put("nums", 210);
        record.put("t_id", i);
        records.add(record);
    }

    // 批量插入文檔
    mongoTemplate.insert(records, COLLECTION_NAME);

    // 查詢插入的內容
    List<Map> result =
            mongoTemplate.find(new Query(Criteria.where("wechart").is("一灰灰blog")), Map.class, COLLECTION_NAME);
    System.out.println("Query Insert Records: " + result);
}
複製代碼

返回結果以下:mongodb

Query Insert Records: [{t_id=0, wechart=一灰灰blog, _id=5c49b07cd5b7ee435cbe5022, blog=[http://spring.hhui.top, http://blog.hhui.top], nums=210}, {t_id=1, wechart=一灰灰blog, _id=5c49b07cd5b7ee435cbe5023, blog=[http://spring.hhui.top, http://blog.hhui.top], nums=210}, {t_id=2, wechart=一灰灰blog, _id=5c49b07cd5b7ee435cbe5024, blog=[http://spring.hhui.top, http://blog.hhui.top], nums=210}]
複製代碼

3. upsert,不存在才插入

咱們但願在插入以前,判斷數據是否存在,若是不存在則插入;若是存在則更新;此時就能夠採用upsert來使用,通常三個參數數組

mongoTemplate.upsert(Query query, Update update, String collectionName)
複製代碼

第一個爲查詢條件,第二個爲須要更新的字段,最後一個指定對應的collection,一個簡單的實例以下spring-boot

/** * 數據不存在,經過 upsert 新插入一條數據 * * set 表示修改key對應的value * addToSet 表示在數組中新增一條 */
public void upsertNoMatch() {
    // addToSet 表示將數據塞入document的一個數組成員中
    UpdateResult upResult = mongoTemplate.upsert(new Query(Criteria.where("name").is("一灰灰blog").and("age").is(100)),
            new Update().set("age", 120).addToSet("add", "額外增長"), COLLECTION_NAME);
    System.out.println("nomatch upsert return: " + upResult);

    List<JSONObject> re = mongoTemplate
            .find(new Query(Criteria.where("name").is("一灰灰blog").and("age").is(120)), JSONObject.class,
                    COLLECTION_NAME);
    System.out.println("after upsert return should not be null: " + re);
    System.out.println("------------------------------------------");
}
複製代碼

輸出結果以下:學習

nomatch upsert return: AcknowledgedUpdateResult{matchedCount=0, modifiedCount=0, upsertedId=BsonObjectId{value=5c49b07ce6652f7e1add1ea2}}
after upsert return should not be null: [{"add":["額外增長"],"name":"一灰灰blog","_id":{"counter":14491298,"date":1548333180000,"machineIdentifier":15099183,"processIdentifier":32282,"time":1548333180000,"timeSecond":1548333180,"timestamp":1548333180},"age":120}]
------------------------------------------
複製代碼

4. upsert,存在則更新

前面的demo是演示不存在,那麼存在數據呢?

/** * 只有一條數據匹配,upsert 即表示更新 */
public void upsertOneMatch() {
    // 數據存在,使用更新
    UpdateResult result = mongoTemplate.upsert(new Query(Criteria.where("name").is("一灰灰blog").and("age").is(120)),
            new Update().set("age", 100), COLLECTION_NAME);
    System.out.println("one match upsert return: " + result);

    List<JSONObject> ans = mongoTemplate
            .find(new Query(Criteria.where("name").is("一灰灰blog").and("age").is(100)), JSONObject.class,
                    COLLECTION_NAME);
    System.out.println("after update return should be one: " + ans);
    System.out.println("------------------------------------------");
}
複製代碼

輸出結果以下,注意下面的輸出數據的 _id,正視前面插入的那條數據,兩個數據惟一的不一樣,就是age被修改了

one match upsert return: AcknowledgedUpdateResult{matchedCount=1, modifiedCount=1, upsertedId=null}
after update return should be null: [{"add":["額外增長"],"name":"一灰灰blog","_id":{"counter":14491298,"date":1548333180000,"machineIdentifier":15099183,"processIdentifier":32282,"time":1548333180000,"timeSecond":1548333180,"timestamp":1548333180},"age":100}]
複製代碼

5. upsert,多條知足時

若是query條件命中多條數據,怎麼辦?會修改幾條數據呢?

/** * 兩條數據匹配時,upsert 將只會更新一條數據 */
public void upsertTwoMatch() {
    // 多條數據知足條件時,只會修改一條數據
    System.out.println("------------------------------------------");
    List<JSONObject> re = mongoTemplate
            .find(new Query(Criteria.where("name").is("一灰灰blog").and("age").in(Arrays.asList(28, 100))),
                    JSONObject.class, COLLECTION_NAME);
    System.out.println("original record: " + re);

    UpdateResult result = mongoTemplate
            .upsert(new Query(Criteria.where("name").is("一灰灰blog").and("age").in(Arrays.asList(28, 100))),
                    new Update().set("age", 120), COLLECTION_NAME);
    System.out.println("two match upsert return: " + result);

    re = mongoTemplate.find(new Query(Criteria.where("name").is("一灰灰blog").and("age").is(120)), JSONObject.class,
            COLLECTION_NAME);
    System.out.println("after upsert return size should be 1: " + re);
    System.out.println("------------------------------------------");
}
複製代碼

根據實際輸出進行查看,發現只有一條數據被修改;另一條保持不變,結果以下

------------------------------------------
original record: [{"name":"一灰灰blog","_id":{"counter":12472353,"date":1548333180000,"machineIdentifier":14006254,"processIdentifier":17244,"time":1548333180000,"timeSecond":1548333180,"timestamp":1548333180},"age":28,"desc":"歡迎關注一灰灰Blog"}, {"add":["額外增長"],"name":"一灰灰blog","_id":{"counter":14491298,"date":1548333180000,"machineIdentifier":15099183,"processIdentifier":32282,"time":1548333180000,"timeSecond":1548333180,"timestamp":1548333180},"age":100}]
two match upsert return: AcknowledgedUpdateResult{matchedCount=1, modifiedCount=1, upsertedId=null}
after upsert return size should be 1: [{"name":"一灰灰blog","_id":{"counter":12472353,"date":1548333180000,"machineIdentifier":14006254,"processIdentifier":17244,"time":1548333180000,"timeSecond":1548333180,"timestamp":1548333180},"age":120,"desc":"歡迎關注一灰灰Blog"}]
------------------------------------------
複製代碼

II. 其餘

0. 項目

相關博文

1. 一灰灰Blog

一灰灰的我的博客,記錄全部學習和工做中的博文,歡迎你們前去逛逛

2. 聲明

盡信書則不如,以上內容,純屬一家之言,因我的能力有限,不免有疏漏和錯誤之處,如發現bug或者有更好的建議,歡迎批評指正,不吝感激

3. 掃描關注

一灰灰blog

QrCode

知識星球

goals
相關文章
相關標籤/搜索