情境描述:
現有類似 {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 文檔
找到目前比較好的辦法:
設定 key
為 unique
index。
當使用db.collection.insertMany()
插入多文檔時,使用ordered: false
選項跳過插入錯誤的文檔,不中斷插入操作。
最後對插入重複值拋出的異常做處理。
例如:
此處用 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);
}