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.
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 }
)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 } }
)Exercise: MongoDB Query API
What is the MongoDB Query API primarily used for?