给定一个id列表,查询集合中不存在哪些ID的最佳方法是什么? [英] Given a list of ids, what's the best way to query which ids do not exist in the collection?
问题描述
我有一组包含唯一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只能使用内置函数(否则我建议使用设置
),但您可以尝试在列表中找到所有不同的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.
类似(未经测试):
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);
}
}
这篇关于给定一个id列表,查询集合中不存在哪些ID的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!