Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if every element in array matches condition

I have a collection of documents:

date: Date users: [   { user: 1, group: 1 }   { user: 5, group: 2 } ]  date: Date users: [   { user: 1, group: 1 }   { user: 3, group: 2 } ] 

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;   }); } 

Unfortunately, this seems to hurt performance is stated in the $where docs:

$where evaluates JavaScript and cannot take advantage of indexes.

How can I improve this query?

like image 979
Wex Avatar asked May 11 '14 16:05

Wex


People also ask

How do you check if all values in array are true?

To check if all of the values in an array are equal to true , use the every() method to iterate over the array and compare each value to true , e.g. arr. every(value => value === true) . The every method will return true if the condition is met for all array elements.

How do you check if an array is in if condition?

Checking array elements using the for loop First, initialize the result variable to true . Second, iterate over the elements of the numbers array and check whether each element is less than or equal zero. If it is the case, set the result variable to false and terminate the loop immediately using the break statement.

How do you check all values of an array are equal or not in JavaScript?

In order to check whether every value of your records/array is equal to each other or not, you can use this function. allEqual() function returns true if the all records of a collection are equal and false otherwise.


1 Answers

The query you want is this:

db.collection.find({"users":{"$not":{"$elemMatch":{"user":{$nin:[1,5,7]}}}}}) 

This says find me all documents that don't have elements that are outside of the list 1,5,7.

like image 75
Asya Kamsky Avatar answered Sep 30 '22 05:09

Asya Kamsky