skip to content
Alvin Lucillo

Aggregation match stage

/ 1 min read

Aggregation allows the use of multi-stage aggregation to filter and transform data. One example of an aggregation stage is $match.

List all documents with find

db.sightings.find({})
[
  {
    _id: ObjectId('62cf2f0acfe5bbb25ee815fb'),
    species_common: 'Eastern Bluebird',
    species_scientific: 'Sialia sialis',
    date: ISODate('2022-01-17T18:24:00.000Z'),
    location: { type: 'Point', coordinates: [ 41, -74 ] }
  },
  {
    _id: ObjectId('62cf8ebfbb9cdbee29caab04'),
    species_common: 'Eastern Bluebird',
    species_scientific: 'Sialia sialis',
    date: ISODate('2022-01-18T21:09:00.000Z'),
    location: { type: 'Point', coordinates: [ 40, -74 ] }
  },
  {
    _id: ObjectId('62e2d811b1d5bc85b6e04013'),
    species_common: 'Northern Cardinal',
    species_scientific: 'Cardinalis Cardinalis',
    date: ISODate('2022-01-18T05:30:40.000Z'),
    location: { type: 'Point', coordinates: [ 41, -74 ] }
  }
]

With $match, we can filter the data we want for the next aggregation stages. The aggregate function receives an array of stages.

db.sightings.aggregate([{$match: { species_common: "Eastern Bluebird"}}])
[
  {
    _id: ObjectId('62cf2f0acfe5bbb25ee815fb'),
    species_common: 'Eastern Bluebird',
    species_scientific: 'Sialia sialis',
    date: ISODate('2022-01-17T18:24:00.000Z'),
    location: { type: 'Point', coordinates: [ 41, -74 ] }
  },
  {
    _id: ObjectId('62cf8ebfbb9cdbee29caab04'),
    species_common: 'Eastern Bluebird',
    species_scientific: 'Sialia sialis',
    date: ISODate('2022-01-18T21:09:00.000Z'),
    location: { type: 'Point', coordinates: [ 40, -74 ] }
  }
]