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


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: 若新增數據的主鍵已經存在,則會對當前已經存在的數據進行修改操作。


免責聲明!

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



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