MongoDb - MongoDB Query API

1. What is MongoDB Query API?

The Query API in MongoDB is the interface that allows developers to interact with the database to:

  • Retrieve documents (find)

  • Insert new documents (insertOne, insertMany)

  • Update existing documents (updateOne, updateMany, replaceOne)

  • Delete documents (deleteOne, deleteMany)

  • Perform aggregations and searches

It provides a declarative, JSON-like syntax to express what you want to query, filter, or modify.
Instead of writing SQL (as in relational databases), MongoDB uses documents (BSON/JSON) and operators for queries.


2. Query Structure

A MongoDB query typically looks like this:

db.collection.find(
  <filter>,   // conditions to match documents
  <projection> // optional: fields to return
)

Example:

db.users.find(
  { age: { $gt: 25 } },   // filter
  { name: 1, email: 1 }   // projection (only include name & email)
)

3. Core CRUD Operations

a) Read (Finding Documents)

  • findOne() → returns a single matching document

  • find() → returns all matching documents (cursor)

Operators for filtering:

  • Comparison operators:

    • $eq, $ne, $gt, $gte, $lt, $lte

    db.products.find({ price: { $gt: 100 } })
    
  • Logical operators:

    • $and, $or, $not, $nor

    db.users.find({ $or: [ { age: { $lt: 18 } }, { age: { $gt: 60 } } ] })
    
  • Element operators:

    • $exists, $type

    db.users.find({ email: { $exists: true } })
    
  • Array operators:

    • $in, $nin, $all, $size, $elemMatch

    db.orders.find({ items: { $all: ["pen", "notebook"] } })
    

b) Insert (Adding Documents)

db.users.insertOne({ name: "Alice", age: 30 })
db.users.insertMany([{ name: "Bob" }, { name: "Charlie" }])

c) Update (Modifying Documents)

  • updateOne()

  • updateMany()

  • replaceOne()

Common update operators:

  • $set, $unset, $inc, $push, $pull, $addToSet

db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 31 }, $inc: { loginCount: 1 } }
)

d) Delete (Removing Documents)

db.users.deleteOne({ name: "Alice" })
db.users.deleteMany({ inactive: true })

4. Projection (Selecting Fields)

Controls which fields appear in results:

db.users.find(
  { age: { $gt: 20 } },
  { name: 1, email: 1, _id: 0 } // include name & email, exclude _id
)

5. Sorting, Limiting, Skipping

  • sort() → order results

  • limit() → restrict number of docs

  • skip() → skip a number of docs

db.users.find().sort({ age: -1 }).limit(5).skip(10)

6. Aggregation Framework (Advanced Queries)

The Query API also integrates with aggregation pipelines for complex transformations:

db.sales.aggregate([
  { $match: { status: "completed" } },
  { $group: { _id: "$customerId", total: { $sum: "$amount" } } },
  { $sort: { total: -1 } }
])

7. Indexes and Query Performance

  • MongoDB queries can use indexes for speed.

  • You can create indexes:

db.users.createIndex({ email: 1 })
  • Explain queries with:

db.users.find({ email: "[email protected]" }).explain("executionStats")

8. Special Query APIs

  • Text search (with text indexes)

db.articles.find({ $text: { $search: "mongodb query" } })
  • Geospatial queries (for location-based data)

db.places.find({
  location: {
    $near: {
      $geometry: { type: "Point", coordinates: [40, -73] },
      $maxDistance: 5000
    }
  }
})
  • Aggregation operators ($lookup, $unwind, $project) for joins and reshaping.


9. Drivers and Query API Access

The Query API is exposed in:

  • Mongo Shell / mongosh (CLI)

  • Drivers (Node.js, Python, Java, C#, etc.)

  • Atlas API / MongoDB Compass (GUI)


10. Key Takeaways

  • MongoDB Query API is document-oriented (JSON-like).

  • CRUD operations use expressive operators ($eq, $gt, $set, $push, etc.).

  • It supports rich queries, projections, aggregations, and indexes.

  • Queries scale from simple lookups to complex analytics with the same consistent API.