Given a list of ids, what#39;s the best way to query which ids do not exist in the collection?(给定一个 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);
}
}
这篇关于给定一个 id 列表,查询集合中不存在哪些 id 的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:给定一个 id 列表,查询集合中不存在哪些 id 的最佳方法是什么?


基础教程推荐
- Chart.js 在线性图表上拖动点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01