我正在使用insertMany来插入从spotify api收集的文档,其结构如下:
{
spotify_id: "6400dnyeDyD2mIFHfkwHXN",
name: "Pablo Honey",
...
}
用:
db.collection.insertMany(albums)
(其中 albums 是包含上述结构对象的数组(
在随后的调用中,相同的操作运行,但我只想插入新文档,即不插入数据库中已经存在spotify_id
的文档
假设你想要一个关于spotify_id
的唯一索引,那么你可以用它加insertMany
和ordered = 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"}
]
);