Being Part of the $in Crowd

in Querying

Everyone wants to be part of the in-crowd, but not everyone can …

Say you have a couple people represented in Documents like this:

{ "_id" : ObjectId("497ce96f395f2f052a494fd4"),
  person : "Kim", crowd : "cool" }
{ "_id" : ObjectId("497ce96f395f2f052a494fd5"),
  person : "Steve", crowd : "losers" }
{ "_id" : ObjectId("497ce96f395f2f052a494fd6"),
  person : "Ji Sung", crowd : "coolest" }
{ "_id" : ObjectId("497ce96f395f2f052a494fd7"),
  person : "Nigel", crowd : "cool" }
{ "_id" : ObjectId("497ce96f395f2f052a494fd7"),
  person : "Bono" }
{ "_id" : ObjectId("497ce96f395f2f052a494fd8"),
  person : "Robert", crowd : "okay" }
{ "_id" : ObjectId("497ce96f395f2f052a494fd9"),
  person : "William", crowd : "losers" }

Those Poor Losers

Now we only want to get back people that are in the … the in-crowd.

Our in-crowd consists of the “coolest”, “cool”, and “okay” people (we are being nice) but not the “losers” …

Here is how we do it, with the $in operator.

> db.people.find({ crowd : { $in: ["coolest","cool","okay"] }});

See, wasn’t that easy?

15 Year Later: When the Losers are Rich

Now, we all know that a lot of the so-called “losers” in High School turned out to be us, the now successful computer people!

Say we want to do the query the other way around … we can use the Nine Inch Nails operator also known as the $nin operator:

> db.people.find({ crowd : { $nin: ["coolest","cool"] }});

Now we will only get back the “losers” and the “okay” people (we are being nice) … so the in-crowd can hit them up for a job.

The Bono Factor

None of those “cool” kids in High School are hanging out with Bono like Bill Gates!

Note: Bono would have come back in the above query since he isn’t in any crowd! See above.