Introduction to MongoDb with .NET part 7: logical operators


In the previous post we started looking at logical operators in MongoDb. In particular we saw several examples of using the $gt and $lt operators which stand for greater-than and less-than. We don’t use the mathematical symbols ” for this purpose. Instead, operators are used with sub-documents that are manifested as extended JSON documents. We can chain multiple filters separated by a comma which amounts to an AND operation: the city must have a population of at least 50000 and be located in the state of Texas.

In this post we’ll look at the logical operators $and and $or, $not and $nor.

Logical operators

All logical operators with the exception of $not are followed by an array of filters that are chained together by the respective operator. We saw an example of the $and operator in the previous post:

db.zipcodes.find({$and : [{"pop": {$lte: 60000,$gt: 50000}},{"state": "MA"}]})

Notice the array of filters after the $and operator. The query means the following:

  • Population must be greater than 50000 and less than or equal to 60000
  • Furthermore, the city must be located in the state “MA”, i.e. Massachusets

Only those documents are returned that match all the criteria in the array, i.e. within the square brackets. However, the $and operator is not used very often as AND queries can simply be chained in a comma separated list like here:

db.zipcodes.find({"pop" : {$lte : 60000, $gt : 50000}, "state" : "MA"})

I think you’ll agree that this shorter version is simpler.

The $or operator works in much the same way, except that it cannot be simplified. We must keep to the notation where the filters are provided in an array. However, this time the logical operator will be OR, such as “the population must exceed 50000 OR the city must be located in North Dakota”.

Let’s take an example from the restaurants collection this time. We’ll search for restaurants whose cuisine is Chinese OR is located in Manhattan:

db.restaurants.find({$or: [{"cuisine" : "Chinese"}, {"borough" : "Manhattan"}]})

Here’s an example:

        "_id" : ObjectId("56edc2ff03a1cd840734dbab"),
        "address" : {
                "building" : "351",
                "coord" : [
                "street" : "West   57 Street",
                "zipcode" : "10019"
        "borough" : "Manhattan",
        "cuisine" : "Irish",
        "grades" : [
                        "date" : ISODate("2014-09-06T00:00:00Z"),
                        "grade" : "A",
                        "score" : 2
                        "date" : ISODate("2013-07-22T00:00:00Z"),
                        "grade" : "A",
                        "score" : 11
                        "date" : ISODate("2012-07-31T00:00:00Z"),
                        "grade" : "A",
                        "score" : 12
                        "date" : ISODate("2011-12-29T00:00:00Z"),
                        "grade" : "A",
                        "score" : 12
        "name" : "Dj Reynolds Pub And Restaurant",
        "restaurant_id" : "30191841"

There’s not much else to discuss about these operators. There’s also a $nor operator which negates $or so that it becomes a NOR condition. It has the same syntax as $or and returns the documents that fail all the filters in the array. E.g. we can find all restaurants whose cuisine is NOT Chinese and is NOT located in Manhattan as follows:

db.restaurants.find({$nor: [{"cuisine" : "Chinese"}, {"borough" : "Manhattan"}]})

Furthermore we have a $not operator which simply inverts the filter, e.g. here’s a query to find all restaurants that are NOT located in Manhattan:

db.restaurants.find({"borough" : {$not : {$eq : "Manhattan"}}})

What is $eq? Why can’t we just write the following?

db.restaurants.find({"borough" : {$not : "Manhattan"}})

$eq is the “is equal to” operator and $not requires a sub-document. So the $eq operator comes in very handy here.

The next post will take up searches in arrays.

You can view all posts related to data storage on this blog here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Introduction to MongoDb with .NET part 7: logical operators

  1. manatico4 says:

    Hi Andras, very nice tutorials here! I’m following your lessons and all are very friendly and clear to me.
    In the $not – “Manhattan” example I get the “$not needs a regex or document” error, so I changed the line to:
    db.restaurants.find({“borough”: { “$not” : /Manhattan/ } })

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


A great site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: