检查数组中的每个元素是否符合条件 [英] Check if every element in array matches condition
问题描述
我有一组文档:
date: Date
users: [
{ user: 1, group: 1 }
{ user: 5, group: 2 }
]
date: Date
users: [
{ user: 1, group: 1 }
{ user: 3, group: 2 }
]
我想对该集合进行查询,以查找我的用户数组中的每个用户 ID 都在另一个数组 [1, 5, 7] 中的所有文档.在这个例子中,只有第一个文档匹配.
I would like to query against this collection to find all documents where every user id in my array of users is in another array, [1, 5, 7]. In this example, only the first document matches.
我能找到的最佳解决方案是:
The best solution I've been able to find is to do:
$where: function() {
var ids = [1, 5, 7];
return this.users.every(function(u) {
return ids.indexOf(u.user) !== -1;
});
}
不幸的是,这似乎会影响性能,$where 文档中有说明:
Unfortunately, this seems to hurt performance is stated in the $where docs:
$where 评估 JavaScript,不能利用索引.
$where evaluates JavaScript and cannot take advantage of indexes.
如何改进此查询?
推荐答案
你想要的查询是这样的:
The query you want is this:
db.collection.find({"users":{"$not":{"$elemMatch":{"user":{$nin:[1,5,7]}}}}})
这表示找到所有不包含列表 1、5、7 之外元素的文档.
This says find me all documents that don't have elements that are outside of the list 1,5,7.
这篇关于检查数组中的每个元素是否符合条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!