MongoDB Basic Shell Commands (part-4)

MongoDB Basic Shell Commands (part-4)

MongoDB Basic Shell Commands (part-3)

Expressive Query Operator : $expr

$expr => Expressive

  • $expr allows the use of aggregation expressions within the query language. Syntax: { $expr: { <expression> } }
  • $expr allows us to use variables and conditional statements.

A little about the $ sign:

  • $ denotes the use of an operator.
  • $ addresses the field value as a variable.

One of the documents that the following query matches where the trip started and ended at the same station from the trips collection:

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

may look like the following, notice the start station id and end station id field values, inside the query they are following a $ sign which turns them into a variable. $eq operator denotes their values need to be equal to match this query.

{
        "_id" : ObjectId("572bb8222b288919b68abf6b"),
        "tripduration" : 398,
        "start station id" : 483,
        "start station name" : "E 12 St & 3 Ave",
        "end station id" : 483,
        "end station name" : "E 12 St & 3 Ave",
        "bikeid" : 15721,
        "usertype" : "Subscriber",
        "birth year" : 1972,
        "gender" : 2,
        "start station location" : {
                "type" : "Point",
                "coordinates" : [
                        -73.98889957,
                        40.73223272
                ]
        },
        "end station location" : {
                "type" : "Point",
                "coordinates" : [
                        -73.98889957,
                        40.73223272
                ]
        },
        "start time" : ISODate("2016-01-01T00:09:19Z"),
        "stop time" : ISODate("2016-01-01T00:15:58Z")
}

$ addressing the field value:

image.png

Let us find the query which matches 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" ]}
                       ]}})

Let us take a closer look at the query :

image.png

You can see clearly the difference between MQL syntax and Aggregation syntax of the comparison operator, don't worry, we will cover the Aggregation pipeline and operator in details in a later blog of this series.

So in a nutshell $expr=> Expressive Query Operator :

  • Allows for more complex queries and for comparing fields within a document.
  • The $ can be used to access the field value.
  • Syntax for comparison operators using aggregation:

    { <operator> : { <field> , <value>} }

In part-5 we will discuss Array Operators, Projection, and many more interesting topics.

Thanks for reading, any correction or recommendation is welcome.