检查数组中的每个元素是否都符合条件 [英] Check if every element in array matches condition

查看:75
本文介绍了检查数组中的每个元素是否都符合条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组文件:

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 docs中指出: /p>

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆