Skip to content

Expressive Queries

Estimated time to read: 1 minute

Overview

$expr allows the usage of aggregation expressions within the query language. $expr also allows the usage of variables and conditional statements. It is an effective tool for comparing fields within a document by creating a variable of the value.

Syntax

The syntax of the $expr operator is:

{ $expr: { <expression> } }

Usage

$expr can be used in many ways to query the database. In the example below, rather than manually having to construct a query using comparison operators to see if a person started and stopped a journey at the same location, a expressive query can be used instead.

Find all documents where the trip started and ended at the same station:

db.trips.find( { "$expr": { "$eq": [ "$end station id", "$start station id"] } } ).count()

Note

$ addresses the field value. This signifies that the value of the field is requested, not the field itself. It effectively acts as a variable for the value.

$expr can also be combined with Logic Operators to return a result. For example:

To find all documents where the trip lasted longer than 1200 seconds, and started and ended at the same station:

db.trips.find({ "$expr": { 
                        "$and": [ 
                            { "$gt": [ "$tripduration", 1200 ]},
                            { "$eq": [ "$end station id", "$start station id" ]}
                        ]
                    }
                }
            ).count()