Skip to content

Logic Operators

Estimated time to read: 1 minute

Overview

  • $and returns documents that match all of the specified query clauses

  • $or returns documents that at least one of the query clauses are matches

  • $nor returns documents that fail to match both query clauses

  • $not negates the query clause requirement and returns all documents that do not match the query

Syntax

For $and, $or, $nor, the syntax is:

{ <operator> : [ statement1}, {statement2}, ...] }

For $not, the syntax is:

{$not : {statement}}

Implict $and

$and is used as the default operator when an operator is not specified.

For example:

{sector : "Mobile Food Vendor - 881", result: "Warning"}

is the same as:

{"$and": [{sector : "Mobile Food Vendor - 881", result: "Warning"}]}

Query Simplification

{"$and": [ {"student_id" : {"$gt" : 25} }, {"student_id" : {"$lt" : 100} } ]}

can be simplified to

{"student_id": {"$gt" : 25, "$lt": 100}}

Explicit $and

When you need to include the same operator more than once in a query.

{"$or": [ {dst_airport : "KZN"}, {src_airport : "KZN"} ] }

and

`{"$or": [ {airplane : "CR2"}, {airplane : "A81"} ] }

Find all documents where airplanes CR2 or A81 left or landed in the KZN airport:

db.routes.find({ "$and": [ { "$or" :[ { "dst_airport": "KZN" },
                                    { "src_airport": "KZN" }
                                  ] },
                          { "$or" :[ { "airplane": "CR2" },
                                     { "airplane": "A81" } ] }
                         ]}).pretty()