TExcelTAD
Home › MongoDB › MongoDB Query API

MongoDB Query API

The MongoDB Query API is the set of methods and operators you use to talk to the database. The same API is available everywhere: in mongosh, in every official driver (Node.js, Python, Java, C#, Go, …) and in tools like MongoDB Compass. Learn it once in mongosh and you can use it from any language.

The two main ways to ask for data

Approach Use it for Example
CRUD methods create, read, update and delete individual documents db.products.find({ category: 'tea' })
Aggregation pipelines transform, group, join and summarise many documents db.orders.aggregate([{ $group: … }])

The shape of a call

Almost every method follows the same pattern:

js
db.<collection>.<method>(<filter>, <second argument>, <options>)
  • The filter (also called a query) is a document that describes which documents to touch. {} means "all of them".
  • The second argument depends on the method: a projection for find (which fields to return), an update document for updateOne, and so on.
  • The options fine-tune the call, for example { upsert: true }.

Filters are documents too, so they are easy to build in code. The simplest filter matches a field by equality:

mongosh · try it yourself
print(db.products.find({ category: 'tea' }, { name: 1, price: 1 }).toArray());
[
  { _id: 6, name: 'Green Sencha', price: 12 },
  { _id: 7, name: 'Earl Grey', price: 9.5 },
  { _id: 8, name: 'Chamomile Calm', price: 8 },
  { _id: 9, name: 'Masala Chai', price: 11 }
]

To compare instead of matching exactly, the value becomes a small document with an operator. Operators start with $:

mongosh · try it yourself
const filter = { category: 'coffee', price: { $gte: 20 } };
print(db.products.countDocuments(filter));
db.products.find(filter).forEach(p => print(p.name, p.price));
3
Espresso Beans 24.5
Ethiopia Yirgacheffe 27
Colombia Supremo 21

The CRUD methods

Operation Methods
Create insertOne(doc), insertMany([docs])
Read find(filter, projection), findOne(filter, projection), countDocuments(filter), distinct(field, filter)
Update updateOne(filter, update), updateMany(filter, update), replaceOne(filter, doc), findOneAndUpdate(…)
Delete deleteOne(filter), deleteMany(filter), findOneAndDelete(filter)
Many at once bulkWrite([operations])

The write methods return a small result document describing what happened:

mongosh · try it yourself
const result = db.products.updateOne({ _id: 7 }, { $inc: { stock: -2 } });
print(result);
print(db.products.findOne({ _id: 7 }, { name: 1, stock: 1 }));
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
{ _id: 7, name: 'Earl Grey', stock: 78 }

matchedCount tells you how many documents the filter found; modifiedCount how many actually changed.

Aggregation in one example

An aggregation pipeline is an array of stages. Documents flow through them in order, and each stage transforms the stream. This pipeline keeps the delivered orders, groups them by customer and sorts by money spent:

mongosh · try it yourself
print(db.orders.aggregate([
  { $match: { status: 'delivered' } },
  { $group: { _id: '$customerId', orders: { $sum: 1 }, spent: { $sum: '$total' } } },
  { $sort: { spent: -1, _id: 1 } },
  { $limit: 3 }
]).toArray());
[
  { _id: 1, orders: 2, spent: 114 },
  { _id: 3, orders: 2, spent: 104.5 },
  { _id: 5, orders: 1, spent: 89 }
]

You will learn every one of these stages in the Aggregation section of this course.

Query operator families

Family Operators Lesson
Comparison $eq $ne $gt $gte $lt $lte $in $nin Query Operators
Logical $and $or $nor $not Query Operators
Element $exists $type Documents and BSON Types
Evaluation $regex $expr $mod $text Query Operators
Array $all $elemMatch $size Querying Arrays
Update $set $unset $inc $push $pull … Update Operators

Note: Operators work anywhere in the filter, including on nested fields reached with dot notation: { 'address.country': 'UK' }.

Test yourself

What does the filter {} match?

  1. Nothing
  2. Every document in the collection
  3. Only documents without fields
  4. It is an error

How do you write "price greater than 10" in a filter?

  1. { price > 10 }
  2. { price: '>10' }
  3. { price: { $gt: 10 } }
  4. { $gt: { price: 10 } }

Which tool would you reach for to compute the total revenue per customer?

  1. find() with a projection
  2. updateMany()
  3. An aggregation pipeline with $group
  4. countDocuments()