42

我有一个要删除的 mongo '_id' 列表。目前我正在这样做

# inactive_users -->  list of inactive users 
for item in inactive_users:
    db.users.remove({'_id' : item})

但我的问题是列表太大了……(可能超过 100,000 个)。因此查询列表中的每个项目只会增加服务器的负载。他们是一种在 mongo 查询中传递整个列表的方法,这样我就不必一次又一次地触发查询。

谢谢

4

5 回答 5

95
db.users.deleteMany({'_id':{'$in':inactive_users}})
于 2013-09-02T06:45:14.557 回答
21

将它们全部列出并使用$in运算符:

db.users.remove({_id:{$in:[id1, id2, id3, ... ]}})
于 2013-09-02T06:40:31.747 回答
7

您需要使用以下方式以特定格式传递 id ObjectId()

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

Remove不接受整数 - 您必须使用ObjectId格式_idstring.

于 2016-03-22T17:06:57.103 回答
4
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);
});
于 2016-06-03T00:12:01.177 回答
2

我有同样的问题并遇到了这些答案,但似乎 MongoDB 手册建议使用 deleteMany 而不是删除。deleteMany 返回删除计数以及写入问题的确认(如果操作成功)。

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

或使用箭头功能:

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

或者更好的是,有一个承诺:

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);
});
于 2019-02-18T23:31:47.843 回答