MongoDB Queries
What Is Queries?
Reading data in MongoDB starts with db.collection.find(filter, projection). The filter is a document that describes what to match, the optional projection chooses which fields to return, and cursor methods such as sort(), limit(), and skip() shape the result. Filters use query operators such as $gt, $in, and $or when simple equality is not enough.
Why It Matters
| Reason | Benefit |
|---|---|
| Fetch only what you need | Projection reduces network traffic and memory when documents are large. |
| Expressive filters | Comparison and logical operators cover ranges, sets, and combined conditions. |
| Predictable ordering | sort plus limit gives you top-N and pagination patterns. |
| Index friendly | Well-formed filters let MongoDB use an index instead of scanning the collection. |
How To Use It
- Seed a movies collection with a few documents containing title, year, rating, and genres.
- Run db.movies.find() to see everything, then add a simple equality filter.
- Use a range such as { year: { $gte: 2010, $lt: 2020 } }.
- Match sets with $in and combine conditions with $or.
- Add a projection as the second argument to return only title and year.
- Chain .sort({ rating: -1 }).limit(3) for a top-three list.
- Use .skip() with .limit() for simple paging, and prefer range queries on large offsets.
mongosh Examples
db.movies.insertMany([
{ title: "Inception", year: 2010, rating: 8.8, genres: ["sci-fi", "thriller"] },
{ title: "Parasite", year: 2019, rating: 8.5, genres: ["thriller", "drama"] },
{ title: "Up", year: 2009, rating: 8.3, genres: ["animation"] },
{ title: "Tenet", year: 2020, rating: 7.3, genres: ["sci-fi"] }
])
// Equality and range
db.movies.find({ year: { $gte: 2010, $lt: 2020 } })
// $in and $or
db.movies.find({ genres: { $in: ["sci-fi", "animation"] } })
db.movies.find({ $or: [{ rating: { $gt: 8.5 } }, { year: 2020 }] })
// Projection: only title and year
db.movies.find({ rating: { $gt: 8 } }, { title: 1, year: 1, _id: 0 })
// Top 2 by rating
db.movies.find().sort({ rating: -1 }).limit(2)
// Simple paging: page 2 with 2 per page
db.movies.find().sort({ year: 1 }).skip(2).limit(2) Edge Cases & Pitfalls
Do not mix include and exclude in projection
Apart from _id, a projection must either include fields (1) or exclude fields (0), not both.
Large skip values are slow
skip() still walks past the skipped documents. For deep paging, filter on the last seen sort value instead.
Type matters
{ age: 30 } does not match the string "30". Store consistent types.
Sorting without an index
A big sort without a supporting index can exceed the in-memory sort limit. Add an index on the sort field.
Cheat Sheet
| Topic | Detail |
|---|---|
| { field: value } | Equality match; several fields combine with AND |
| $eq $ne | Equal and not equal |
| $gt $gte $lt $lte | Greater than, greater or equal, less than, less or equal |
| $in $nin | Match any (or none) of the values in an array |
| $and $or $nor | Combine filters; takes an array of filter documents |
| $not | Invert a single operator expression |
| $exists | Match documents that have (or lack) a field |
| Projection { a: 1, _id: 0 } | Include listed fields; _id is returned unless set to 0 |
| sort({ a: 1 }) | 1 for ascending, -1 for descending |
| limit(n) / skip(n) | Cap the result size and skip leading documents |
Key Takeaways
A filter with several fields is an implicit $and. Use $or explicitly when any one condition may match, and always index the fields you filter and sort on.
Frequently Asked Questions
How do I find documents by multiple conditions?
Put several fields in one filter for an implicit AND, or use $and and $or with arrays of conditions for explicit control.
How do I return only certain fields?
Pass a projection as the second argument, such as { title: 1, year: 1 }. Add _id: 0 to hide the _id field.
How do I sort results?
Chain sort() with 1 for ascending and -1 for descending, for example find().sort({ rating: -1 }).
What is the difference between $in and $or?
$in tests one field against a list of values. $or combines separate conditions that can involve different fields.
How do I get the first N results?
Use sort() then limit(N). Without a sort, the order is not guaranteed.
Does find return all documents at once?
No. It returns a cursor. In mongosh it prints the first batch, and you can type it to fetch more.
Next: MongoDB Update Operations
Continue the MongoDB learning path.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
8 people found this page helpful
