给定一个 id 列表,查询集合中不存在哪些 id 的最佳方法是什么?

我有一组包含唯一 id 字段的文档.现在我有一个 id 列表,其中可能包含一些集合中不存在的 id.从列表中找出这些 id 的最佳方法是什么?

I have a collection of documents which contain unique id field. Now I have a list of ids which may contain some ids that do not exist in the collection. What's the best way to find out those ids from the list?

我知道我可以使用 $in 运算符来获取列表中包含 id 的文档,然后与给定的 id 列表进行比较,但是有更好的方法吗?

I know I can use $in operator to get the documents which have ids contained in the list then compare with the given id list, but is there better way to do it?

推荐答案

不幸的是 MongoDB 只能使用内置函数(否则我建议使用 set)但你可以尝试找到所有不同的id 在您的列表中,然后手动将其拉出.

Unfortunately MongoDB can only use built in functions (otherwise I'd recommend using a set) but you could try and find all distinct id's in your list then just manually pull them out.

类似的东西(未经测试):

Something like (untested):

var your_unique_ids = ["present", "not_present"];

var present_ids = db.getCollection('your_col').distinct('unique_field', {unique_field: {$in: your_unique_ids}});

for (var i=0; i < your_unique_ids.length; i++) {
    var some_id = your_unique_ids[i];
    if (present_ids.indexOf(some_id) < 0) {
        print(some_id);
    }
}

相关文章