简体   繁体   English

NodeJS批量删除mongodb文档

[英]NodeJS bulk remove mongodb documents

I have a collection with some bad data. 我有一些不良数据的集合。 I would like to bulk delete this data based on some query. 我想基于一些查询批量删除此数据。 This is easy in the mongo shell as db.collection.remove() allows you to specify the justOne option. 在mongo shell中这很容易,因为db.collection.remove()允许您指定justOne选项。 Is there some way to do this in the node.js driver? 在node.js驱动程序中有什么方法可以做到这一点? findAndRemove seems to only delete 1 document and has no option to make it bulk? findAndRemove似乎只删除1个文档,并且没有使其批量化的选项?

db.collection(collection_name, function(err, collection){
  collection.findAndRemove({type: 'LUXURY'}, function(err, result){
    // result is only a single document
    console.log(result._id.toString());
  });
});

I know an alternative to this is to find() all documents that satisfy my query and manually create a BulkOp using initializeUnorderedBulkOp and populate it by iterating over the results of my find, but I feel there should be an easier way. 我知道一个替代方法是使用find()满足我的查询的所有文档,并使用initializeUnorderedBulkOp手动创建BulkOp,并通过遍历find的结果进行填充,但是我觉得应该有一种更简单的方法。

If you are using node-mongo-native driver, I can't see any reason why you don't use the remove directly. 如果您使用的是node-mongo-native驱动程序,那么我看不到您不直接使用remove的任何原因。

db.collection(collection_name, function(err, collection){
  collection.remove({type: 'LUXURY'}, function(err, result){
    // your code here.
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM