MongoDB Query API

The MongoDB Query API is the set of JSON-based methods — like find, insertOne, updateOne, and deleteOne — that the shell and drivers use to read and write documents.

What Is the Query API?

Unlike SQL, which is a standalone text-based query language, the MongoDB Query API is a family of methods you call directly on a collection object, such as db.orders.find(...). Each method accepts one or more BSON documents as arguments: a filter document to select which records match, and often a second document to shape the results or configure options like sorting and limits.

Filter Documents and Query Operators

A filter document lists the fields you want to match, using either a direct value for an exact match or a query operator for more expressive conditions. Operators always start with a dollar sign, such as $gt for greater-than or $in for matching any value in a list, and multiple conditions can be combined implicitly (treated as AND) or explicitly with $and and $or.

OperatorMeaning
$eq / $neequal to / not equal to
$gt / $gtegreater than / greater than or equal
$lt / $lteless than / less than or equal
$in / $ninvalue is / is not in an array
$and / $orcombine multiple conditions

Common CRUD Methods

  • find() / findOne() — read matching documents
  • insertOne() / insertMany() — create new documents
  • updateOne() / updateMany() — modify existing documents
  • deleteOne() / deleteMany() — remove documents
  • countDocuments() — count matches without loading them

Find with a filter and projection

db.products.find(
  { category: "electronics" },
  { name: 1, price: 1, _id: 0 }
)
Note: The second argument to find() is a projection. Setting a field to 1 includes it and 0 excludes it — using projections keeps result documents small and reduces network traffic.

Query with comparison operators

db.products.find({
  price: { $gt: 20, $lte: 100 },
  category: { $in: ["electronics", "toys"] }
})

Update with the $set operator

db.products.updateOne(
  { name: "Wireless Mouse" },
  { $set: { price: 24.99, onSale: true } }
)
Note: find() does not return an array immediately — it returns a cursor that fetches documents lazily in batches. Calling .toArray() in a driver, or simply letting mongosh print it, iterates that cursor for you.

Exercise: MongoDB Query API

What is the MongoDB Query API primarily used for?