检查数组中的每个元素是否匹配条件 [英] 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.
如何改进这个查询?
推荐答案
你要的查询是这样的:
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屋!
查看全文