Remove multiple documents from mongo in a single query

后端 未结 5 871
栀梦
栀梦 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 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);
    });
    

提交回复
热议问题