MongoDB save()方法和insert()方法的區別

來源:互聯網
上載者:User

標籤:depend   key   sig   依賴   shell   更新   產生   blog   pen   

MongoDB save()方法和insert()方法的區別首先看官方文檔怎麼說的

Updates an existing document or inserts a new document, depending on its document parameter

save方法有更新和插入兩種功能,到底是插入還是更新文檔取決於save的參數。那麼到底是依賴於哪個參數呢?繼續看

If the document does not contain an _id field, then the save() method calls the insert() method. During the operation, the mongo shell will create an ObjectId and assign it to the _id field.

可以看到決定是插入一個文檔還是更新,取決於_id參數。如果能根據_id找到一個已經存在的文檔,那麼就更新。如果沒有傳入_id參數或者找不到存在的文檔,那麼就插入一個新文檔。

舉一個官方的例子

不帶_id參數

db.products.save( { item: "book", qty: 40 } )

結果

{ "_id" : ObjectId("50691737d386d8fadbd6b01d"), "item" : "book", "qty" : 40 }

MongoDb用戶端驅動會自動為你產生一個預設
ObjectId作為_id。

帶_id參數,但是找不到一個已經存在的文檔

db.products.save( { _id: 100, item: "water", qty: 30 } )

結果

{ "_id" : 100, "item" : "water", "qty" : 30 }

還是插入一個新文檔,但是_id不會自動產生。

帶_id參數,但是有存在的文檔

db.products.save( { _id : 100, item : "juice" } )

結果

{ "_id" : 100, "item" : "juice" }

更新了文檔

總結
  1. insert: 若新增資料的主鍵已經存在,則會拋 org.springframework.dao.DuplicateKeyException 異常提示主鍵重複,不儲存當前資料。
  2. save: 若新增資料的主鍵已經存在,則會對當前已經存在的資料進行修改操作。

MongoDB save()方法和insert()方法的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.