Query Methods

Simple aggregation on a single collection — before you need the full pipeline.

Back to Index | Next: 02 - The Aggregation Pipeline


MongoDB provides built-in methods that let you do basic aggregation on a single collection without using the full aggregation framework.

count()

Returns the number of documents in a result set.

// Insert some sample data
db.inventory.insertMany([
  { item: "journal",  qty: 25 },
  { item: "notebook", qty: 50 }
]);
 
// Count all documents in the collection
db.inventory.count();
// → 2
 
// Count documents matching a filter
db.inventory.find({ qty: { $gte: 20 } }).count();
// → 1

When to use: Whenever you need a quick count of documents — total or filtered.


distinct()

Returns an array of all unique values for a given field across the collection.

db.persons.insertMany([
  { name: "Andreas",   age: 21 },
  { name: "Christian", age: 23 }
]);
 
db.persons.distinct("name");
// → ["Andreas", "Christian"]

When to use: When you want to know all possible values a field takes — e.g., all categories, all statuses, all unique names.


Limitations of Query Methods

Query methods only work on a single collection. You cannot:

  • Join data from other collections
  • Chain multiple transformation steps
  • Use advanced expressions or operators

For anything beyond simple counts, distinct values, or basic grouping, you need the Aggregation Pipeline.