MongoDB資料update的坑

來源:互聯網
上載者:User

標籤:last   ted   date   應該   inter   name   nbsp   ocs   ref   

統計mongodb慢查詢的時候,發現有的集合慢查詢很多,然後通知開發看一下欄位加索引,

和開發討論之後加唯一索引,加的時候發現有重複資料,然後用彙總命令統計了一下24w的資料有10w+的重複資料,

開發說update操作的時候加了{upsert:true},應該是查詢不到新增一條,不會有重複資料,

然後查看mongodb的官方文檔查看db.collection.update,其中有以下解釋

Use Unique Indexes

WARNING

To avoid inserting the same document more than once, only use upsert: true if the query field is uniquely indexed.

 

Given a collection named people where no documents have a name field that holds the value Andy. Consider when multiple clients issue the following update with upsert: true at the same time:

db.people.update( { name: "Andy" }, { name: "Andy", rating: 1, score: 1 }, { upsert: true } ) 

If all update() operations complete the query portion before any client successfully inserts data, andthere is no unique index on the name field, then each update operation may result in an insert.

To prevent MongoDB from inserting the same document more than once, create a unique index on the namefield. With a unique index, if multiple applications issue the same update with upsert: true, exactly oneupdate() would successfully insert a new document.

The remaining operations would either:

  • update the newly inserted document, or

  • fail when they attempted to insert a duplicate.

    If the operation fails because of a duplicate index key error, applications may retry the operation which will succeed as an update operation.

 

 

意思大體是說:同時高並發upsert的話,查詢操作完成,但是還沒insert,這時會同時insert多條相同 的資料,為了避免這個問題可以增加唯一索引,也就是說,資料的唯一性只能通過唯一索引來保證,

同時舉例說明了唯一索引然後高並發update的操作情況:

 

  1. 更新已經插入的新的資料
  2. 由於唯一索引insert失敗,然後這種情況最好加一個重試的機制,這樣就可以update成功了。

MongoDB資料update的坑

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.