ZacAttack
ZacAttack

Reputation: 2027

How to find items in an array that are not contained in a MongoDB collection

Say I have an array of city names, and a MongoDB collection of city names. Say that my array looks like:

["San Francisco", "chicago", "New York", "Los Angeles"]

And my collection looks like

{{cityName: "chicago"}
{cityName: "New York"}}

What I'd like to do is perform a query that returns to me San Francisco and Los Angeles. So far, my only idea is to just perform the query, get the matches, and do an array subtraction from the original array (and thus get my cities), but I wonder if theres a way to do it in a one step query.

Thanks in advance!

Upvotes: 0

Views: 126

Answers (3)

Asya Kamsky
Asya Kamsky

Reputation: 42352

You need to perform the following query against your MongoDB collection:

db.cities.distinct("cityName", {cityName:{$in:["new york","los angeles","chicago","san francisco"]}})

This will return the array of cities that matched something in the collection. In your example above you would get back: ["chicago","new york"]

You can now subtract those elements from original array and get the desired result.

The key is to do a distinct query (rather than getting all the results) and pass a query limiting the query to the cities you care about, not all cities that are represented by your collection.

Upvotes: 2

Loïc bcn
Loïc bcn

Reputation: 154

Is there a coma in your collection ?

{{cityName: "chicago"},
{cityName: "New York"}}

If yes, you can do:

for( var i in collec ){
  var cityname = collec[i]['cityname'];
  // if you use jquery
  var getcity = $.grep( yourarray, function(n,i){
   return n == cityname;
  });
  // getcity in an array with all matching elements
  console.log(getcity);
}

Upvotes: 0

Shubhanshu Mishra
Shubhanshu Mishra

Reputation: 6700

The array subtraction is the only way to go ahead with this as even if you use any mongodb driver and if it supports this function, it will eventually be doing the same thing.

A query on MongoDb will always return the values which are either contained in it or a null value. So you have to take the values and do an array subtraction.

Upvotes: 0

Related Questions