Remove multiple documents from mongo in a single query

后端 未结 5 846
栀梦
栀梦 2020-11-30 02:16

I have a list of mongo \'_id\' which I want to delete. Currently I am doing this

# inactive_users -->  list of inactive users 
for item in inactive_users:         


        
相关标签:
5条回答
  • 2020-11-30 02:55
    var collection = db.users;
    var usersDelete = [];
    var ObjectID = req.mongo.ObjectID;   //req is request from express
    
    req.body.forEach(function(item){     //req.body => [{'_id' : ".." , "name" : "john"}]
        usersDelete.push(new ObjectID(item._id));
    });
    
    collection.remove({'_id':{'$in': usersDelete}},function(){
        //res.json(contatos);
    });
    
    0 讨论(0)
  • 2020-11-30 03:02

    You need to pass the ids in a specific format using ObjectId():

    db.users.remove({_id: {$in: [ObjectId('Item1'), ObjectId('Item2'), ObjectId('Item2')]}});
    

    Remove doesn't accept integer - you have to use ObjectId instance with _id format as a string.

    0 讨论(0)
  • 2020-11-30 03:04

    I had the same question and ran across these answers but it seems the MongoDB manual is recommending deleteMany instead of remove. deleteMany returns the delete count as well as an acknowledgement of the write concern (if the operation succeeded).

    const ids = [id1, id2, id3...];
    const query = { _id: { $in: ids} };
    dbo.collection("users").deleteMany(query, function (err, obj) {
        if (err) throw err;
    });
    

    Or with an arrow function:

    const ids = [id1, id2, id3...];
    const query = { _id: { $in: ids} };
    dbo.collection("users").deleteMany(query, (err, obj) => {
        if (err) throw err;
    });
    

    Or better yet, with a promise:

    const ids = [id1, id2, id3...];
    const query = { _id: { $in: ids} };
    dbo.collection("users").deleteMany(query)
    .then(result => {
        console.log("Records Deleted");
        console.log(JSON.stringify(result));
        //for number removed...
        console.log("Removed: " + result["n"]);
    })
    .catch(err => {
        console.log("Error");
        console.log(err);
    });
    
    0 讨论(0)
  • 2020-11-30 03:06

    List them all and use $in operator:

    db.users.remove({_id:{$in:[id1, id2, id3, ... ]}})
    
    0 讨论(0)
  • 2020-11-30 03:13
    db.users.remove({'_id':{'$in':inactive_users}})
    
    0 讨论(0)
提交回复
热议问题