Script Valley
MongoDB: Complete Course
CRUD OperationsLesson 2.2

How to query MongoDB documents with find and filters

find, findOne, equality filters, comparison operators, logical operators, projection, cursor methods, limit and skip

find and findOne

MongoDB find filter

find returns a cursor over all matching documents. findOne returns the first match or null if nothing matches. Passing an empty filter object {} matches every document in the collection. Cursors are lazy โ€” MongoDB does not execute the query until you call .toArray(), iterate, or chain a terminal method.

// findOne โ€” returns one document or null
const product = await db.collection('products').findOne({ name: 'Mouse' })

// find with comparison operators
const mid = await db.collection('products')
  .find({ price: { $gt: 50, $lte: 300 } }).toArray()

// Logical OR
const featured = await db.collection('products').find({
  $or: [{ inStock: true }, { price: { $lt: 20 } }]
}).toArray()

// Implicit AND โ€” multiple fields in the same filter object
db.collection('products').find({ inStock: true, category: 'peripherals' })

Projection โ€” control which fields are returned

The second argument to find limits which fields MongoDB sends over the network. Use 1 to include and 0 to exclude. You cannot mix include and exclude values in the same projection, except you can always explicitly exclude _id alongside inclusions.

// Return only name and price, suppress _id
db.collection('products').find({}, { name: 1, price: 1, _id: 0 })

Cursor control

db.collection('products')
  .find({ inStock: true })
  .sort({ price: -1 })  // descending
  .skip(20).limit(10)   // page 3 of 10-per-page results

Up next

How to update documents in MongoDB with updateOne and updateMany

Sign in to track progress

How to query MongoDB documents with find and filters โ€” CRUD Operations โ€” MongoDB: Complete Course โ€” Script Valley โ€” Script Valley