The MongoDB Query API is extremely powerful. It allows you to interact with your data easily. You can filter, sort, and format results.
The Query API uses JSON-like syntax. You do not need to write long SQL strings. Instead, you pass objects as parameters.
A query filter specifies your conditions. It tells MongoDB exactly what to find. Empty filters return every document in a collection.
Every driver uses this same fundamental API. Whether you use Python, Node.js, or Java. The core concepts never change.
Sometimes documents are huge. You might only want specific fields. Projections let you include or exclude fields.
The Query API lets you sort data fast. You can sort in ascending order (1). Or you can sort in descending order (-1).
// Find active users, sorted by age
const filter = { status: "active" };
const sort = { age: 1 };
db.users.find(filter).sort(sort);
Sometimes you only want the top 5 results. You can use the limit() method. This saves bandwidth and improves performance.
For pagination, you must skip records. Use the skip() method for this. Combining skip and limit builds great pagination.
API methods can be chained together. This creates very clean and readable code. find().sort().limit() is a common pattern.
Keep your queries simple. Use indexes to make queries lightning fast. Always test queries using explain plans.
Which method is used to restrict the number of returned documents?