Skip to main content

πŸ‘ $match

The $match stage filters documents in a collection. It takes a document as input (your filter) and returns the documents that match the specified criteria. The syntax for the $match stage is as follows:

{ $match: { <expression>: <value> } }

Expressions​

The <expression> portion of the $match stage can be any valid MongoDB expression. This includes:

  • Comparison operators: eq, neq, gte, lte, gt, lt, in, nin, exists.
  • Regular expressions: regex.
  • Logical operators: and, or, not.
  • Subdocuments and arrays: { field: <value> }, [ <item>, <item>, ... ].

Matching book documents​

First, make sure you select the books collection in the Atlas UI.

Atlas UI database deployment with the books collection highlighted.

Then, navigate to the Aggregation tab and click </> TEXT.

Atlas UI database deployment with aggregation tab highlighted.

Say we want all the books from the year 2010. We can add a $match stage to filter the documents from the books collection:

[
{
$match: { year: 2010 }
}
]
Atlas AI $match aggregation.

πŸ‘ Return all the books that have exactly 100 pages.

Answer
[
{
$match: { pages: 100 }
}
]

AND​

If we need to add more conditions using AND, we use the $and operator.

If we want all the books with 100 pages and with exactly totalInventory 1, we can use the $and operator. It takes an array of documents with all the conditions that should be true for the AND to succeed:

[
{
$match: {
$and: [
{ pages: 100 },
{ totalInventory: 1 }
]
}
}
]

The pseudo-code for this would be something like:

IF pages == 100 AND totalInventory == 1 {
return matching docs
}

πŸ‘ Return all the books from 2009 that have exactly 192 pages.

Answer
[
{
$match: {
$and: [
{ pages: 192 },
{ year: 2009 }
]
}
}
]

πŸ‘ How many are there? We haven't yet seen the $count stage, but try to adding a second stage to your pipeline with { $count: "books_count" }

Answer
[
{
$match: {
$and: [
{ pages: 100 },
{ year: 2015 }
]
}
},
{
$count: "books_count"
}
]

Shorthand AND​

We can do an implicit AND just passing a document with all the conditions (instead of an array of documents):

[
{
$match: { pages: 100, totalInventory: 2 }
}
]

πŸ‘ Return all the books from 2009 that have exactly 192 pages, using the shorthand $and notation:

Answer
[
{
$match: {pages: 192, year: 2009}
}
]