Reading data is the operation your application will perform most, and in MongoDB it revolves around one method: find(). In this CodeYourCraft lesson you will learn how to filter documents, shape results with projections, sort, paginate, and count, all from the mongosh shell.
Called with no arguments, find() returns every document in a collection as a cursor, while findOne() returns just the first matching document:
use shop
db.products.find() // all products
db.products.findOne() // a single document or nullIn mongosh, a cursor automatically prints the first 20 results, and typing it shows the next batch. In application code you iterate the cursor or convert it to an array.
The first argument to find() is a filter, itself written as a document. A simple filter matches fields by equality:
db.products.find({ price: 2999 })
db.products.find({ name: 'Desk Lamp' })Multiple fields in one filter act as an implicit AND:
db.products.find({ price: 2999, tags: 'video' })Notice that querying tags with a plain string matches any array that contains that value. Array containment queries come free in MongoDB.
To reach inside embedded documents, use dot notation and quote the path:
db.products.find({ 'stock.warehouse': { $gte: 100 } })
db.customers.find({ 'address.city': 'Pune' })Dot notation also works for array positions, so 'tags.0' refers to the first tag.
The second argument to find() is a projection that trims the returned documents, saving bandwidth and memory. Use 1 to include fields and 0 to exclude them:
db.products.find(
{ price: { $lt: 5000 } },
{ name: 1, price: 1, _id: 0 }
)
// [ { name: 'USB-C Cable', price: 499 }, { name: 'Webcam 1080p', price: 2999 }, ... ]You cannot mix inclusion and exclusion in one projection, with one exception: _id, which is included by default, may always be excluded.
Cursors support chainable modifiers that MongoDB applies server-side:
db.products.find({}, { name: 1, price: 1, _id: 0 })
.sort({ price: -1 }) // most expensive first (1 = ascending, -1 = descending)
.skip(10) // skip the first 10
.limit(5) // return at most 5This trio is the classic recipe for pagination, though for large offsets a range-based approach (filtering on the last seen _id or a sort key) is faster because skip still walks the skipped documents.
Use countDocuments for accurate counts with a filter, and estimatedDocumentCount for a fast collection total based on metadata:
db.products.countDocuments({ price: { $lt: 5000 } })
db.products.estimatedDocumentCount()Simple equality only gets you so far. In the next lesson we unlock comparison, logical, and element query operators for far more expressive filters.