Lesson 4 +10 XP

The MongoDB Query API

The MongoDB Query API

The Query API is how you interact with your data in MongoDB. Everything you do - finding documents, updating them, running analytics - goes through it.

Two main ways to use it

  1. CRUD Operations - create, read, update, and delete documents.
  2. Aggregation Pipelines - transform and analyze data in stages.

Where you can run it

The Query API works in many places:

  • mongosh - the MongoDB Shell in your terminal.
  • Compass - MongoDB's GUI.
  • VS Code - with the MongoDB extension.
  • Any driver - Node.js, Python, Java, and more.

What it can do

  • Data transformations with aggregation pipelines.
  • Document joins - combining data across collections with $lookup.
  • Graph and geospatial queries.
  • Full-text search across collections.
  • Indexes for faster queries.
  • Time series analysis.

Example

Even a simple query like this uses the Query API:

db.posts.find({ category: "News" })

And so does a full aggregation pipeline:

db.posts.aggregate([
  { $match: { likes: { $gt: 1 } } },
  { $group: { _id: "$category", totalLikes: { $sum: "$likes" } } }
])

TL;DR

  • The Query API is MongoDB's language for working with data.
  • Two styles: CRUD operations and aggregation pipelines.
  • Available in mongosh, Compass, VS Code, and every driver.