现有类似 {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 文档
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
找到目前比较好的办法:
设置
key为uniqueindex。当使用
db.collection.insertMany()插入多文档时,使用ordered: false选项跳过插入错误的文档,不中断插入操作。最后对插入重复值抛出的异常做处理。
例如:
将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( [
], { ordered: false } );
} catch (e) {
print (e);
}