仅当具有值的键不存在时才插入许多



我正在使用insertMany来插入从spotify api收集的文档,其结构如下:

{
spotify_id: "6400dnyeDyD2mIFHfkwHXN",
name: "Pablo Honey",
...
}

用:

db.collection.insertMany(albums)

(其中 albums 是包含上述结构对象的数组(

在随后的调用中,相同的操作运行,但我只想插入文档,即不插入数据库中已经存在spotify_id的文档

假设你想要一个关于spotify_id的唯一索引,那么你可以用它加insertManyordered = false来继续插入,即使找到一个骗子。 当然,您需要仔细检查错误:

db.foo.drop();
db.foo.createIndex({"spotify_id":1}, {unique:true});
function loadEm(r) {
try {
rc = db.foo.insertMany(r, {ordered:false});
} catch(e) {
// Check for expected dupe errors:                                          
e.getWriteErrors().forEach(function(err) {
if(err.code != 11000) {
// real error!                                                  
throw e;
}
});
}
}
loadEm(
[
{spotify_id: "A", name: "foo"},
{spotify_id: "B", name: "bar"}
]
);

loadEm(
[
{spotify_id: "A", name: "foo"},
{spotify_id: "B", name: "bar"},
{spotify_id: "C", name: "corn"},
{spotify_id: "C", name: "dog"},
{spotify_id: "D", name: "zap"}
]
);

相关内容

  • 没有找到相关文章