MongoDB3.2中插入資料前如何去重

來源:互聯網
上載者:User
關鍵字 mongodb php node.js

情境描述:

現有類似 {key:"value",key1:"value1"} 這樣的文檔。
我使用db.collection.insertMany()將文檔批量插入到集合之中,例如:

db.collection.insertMany([   {key:"1",key1:"value1"},   {key:"2",key1:"value1"},   {key:"3",key1:"value1"},            ……]);

具體問題描述:

我需要key的值是唯一的,在批量插入的時候自動捨棄掉有重複值的文檔。
我有嘗試使用db.collection.createIndex({key:1},{unique:true})給這個集合添加 unique 索引,但結果是插入時如果遇到重複值,直接會中斷插入並且拋出錯誤。

問題:

請問在資料庫層面有沒有解決此問題的辦法?
【修改:】請問在資料庫層面不將唯一值賦給“_id”有沒有解決此問題的辦法?
難道只有在語言層面做判斷?

附:
db.collection.insertMany文檔
unique index 文檔

回複內容:

情境描述:

現有類似 {key:"value",key1:"value1"} 這樣的文檔。
我使用db.collection.insertMany()將文檔批量插入到集合之中,例如:

db.collection.insertMany([   {key:"1",key1:"value1"},   {key:"2",key1:"value1"},   {key:"3",key1:"value1"},            ……]);

具體問題描述:

我需要key的值是唯一的,在批量插入的時候自動捨棄掉有重複值的文檔。
我有嘗試使用db.collection.createIndex({key:1},{unique:true})給這個集合添加 unique 索引,但結果是插入時如果遇到重複值,直接會中斷插入並且拋出錯誤。

問題:

請問在資料庫層面有沒有解決此問題的辦法?
【修改:】請問在資料庫層面不將唯一值賦給“_id”有沒有解決此問題的辦法?
難道只有在語言層面做判斷?

附:
db.collection.insertMany文檔
unique index 文檔

找到目前比較好的辦法:

  1. 設定 keyunique index。

  2. 當使用db.collection.insertMany()插入多文檔時,使用ordered: false 選項跳過插入錯誤的文檔,不中斷插入操作。

  3. 最後對插入重複值拋出的異常做處理。

例如:

此處用 PHP 作為樣本。

try {    //首先對 key 欄位添加唯一索引    $this->collection->createIndex(['key' => 1], ["unique" => true]);} catch (\MongoDB\Driver\Exception\Exception $e) {    Log::error($e->getMessage());}try {    $result = $this->collection->insertMany(        $data,        ['ordered' => false] //跳過插入錯誤    );} catch (\MongoDB\Driver\Exception\BulkWriteException $e) {    /*如果有重複資料插入,將拋出 BulkWriteException */    $result       = $e->getWriteResult();     $writeErrors  = $result->getWriteErrors();     $errorsAmount = count($writeErrors); //插入錯誤的數量    Log::info($errorsAmount . '條重複資料未插入!');} catch (\MongoDB\Driver\Exception\Exception $e) {    Log::error($e->getMessage());    exit;}

將key的值給_id

你看下你自己附帶的文檔,裡面專門有提到的:

With ordered to false, the insert operation would continue with any remaining documents.

Unordered Inserts

The following attempts to insert multiple documents with _id field and ordered: false. The array of documents contains two documents with duplicate _id fields.

try {
db.products.insertMany( [

  { _id: 10, item: "large box", qty: 20 },  { _id: 11, item: "small box", qty: 55 },  { _id: 11, item: "medium box", qty: 30 },  { _id: 12, item: "envelope", qty: 100},  { _id: 13, item: "stamps", qty: 125 },  { _id: 13, item: "tape", qty: 20},  { _id: 14, item: "bubble wrap", qty: 30}

], { ordered: false } );
} catch (e) {
print (e);
}

  • 相關文章

    聯繫我們

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