mongoose一次删除多个数据
我有一个很大的id列表,我想从多个模型中删除mongodb,主要想法是我有多个模式中的文档相同的id,我想从每个模型中删除一个文档。 我正在这样做:
_.each(wrongList, function(item) { UPUSTP.find({id: item.id}).remove(function(err) { if (err) console.log("Error while deleting " + err.message); }) UPUANAM.find({id: item.id}).remove(function(err) { if (err) console.log("Error while deleting " + err.message); }) UPUEXE.find({id: item.id}).remove(function(err) { if (err) console.log("Error while deleting " + err.message); }) UPUEXO.find({id: item.id}).remove(function(err) { if (err) console.log("Error while deleting " + err.message); }) UPUPROC.find({id: item.id}).remove(function(err) { if (err) console.log("Error while deleting " + err.message); }) })
问题是我在错误列表中有14000+个ID,查询起作用,但需要花费很多时间才能完成…我怎样才能增加删除的时间? 我可以批量删除或类似的东西?
我认为你可以在MongoDB的运算符中使用$。
http://docs.mongodb.org/manual/reference/operator/query/in/
就像是:
UTUSTP.remove({_id: {$in: wronglist}}, function(){...}); // and so on
假设你正在使用lo-dash
,你可以用_.pluck
函数获得一个item
id的_.pluck
。 我们称之为idsArray
。 现在,您可以使用$in
操作符,在async.parallel
调用中,使用直接从模型中remove
,如:
async.parallel({ function (callback) { UPUSTP.remove({ id: { $in: idsArray } }, function (err) { if (err) return callback("Error while deleting " + err.message); callback(null, "Some useful message here..."); }); }, . // do the same with the other collections . . function (err, result) { // check the error and do somethin useful with the results }
首先, $in
将把数据库调用减less到每个集合一个。 然后, async.parallel
将并行运行任务,最后直接从模型中删除将删除每个集合的find
操作。