Read Operations Basics
Now that you have data in your database, you need to retrieve it. MongoDB provides powerful query capabilities to find exactly the documents you need. Let's start with the basics: `find()` and `findOne()`.
The find() Method
The `find()` method is used to query documents in a collection. Without any parameters, it returns all documents.
<!-- Get all documents in the posts collection -->db.posts.find()The output will be all documents, but it might be hard to read. Use `pretty()` for better formatting:
db.posts.find().pretty()Think of `find()` as asking "Show me everything" and `pretty()` as "Format it nicely so I can read it".
The findOne() Method
`findOne()` returns only the first document that matches the query. It's useful when you expect only one result or want the first match.
db.posts.findOne()Basic Query Filters
You can pass a query document to `find()` to filter results:
<!-- Find posts by author John -->db.posts.find({ author: "John" }).pretty()
<!-- Find a specific post by title -->db.posts.find({ title: "First Post" }).pretty()
<!-- Find with multiple conditions (AND) -->db.posts.find({ author: "John", tags: "mongodb" }).pretty()Using Projection
Sometimes you don't need all fields. Projection lets you specify which fields to return. Use `1` to include, `0` to exclude.
<!-- Return only title and author, exclude _id -->db.posts.find( { author: "John" }, { title: 1, author: 1, _id: 0 }).pretty()Counting Documents
Use `countDocuments()` to get the number of matching documents:
<!-- Count all posts -->db.posts.countDocuments()
<!-- Count posts by John -->db.posts.countDocuments({ author: "John" })Practical Examples
Let's insert some sample data and try different queries:
<!-- Insert sample data -->db.products.insertMany([ { name: "Laptop", price: 999, category: "electronics" }, { name: "Mouse", price: 25, category: "electronics" }, { name: "Book", price: 15, category: "books" }, { name: "Headphones", price: 50, category: "electronics" }])
<!-- Find all electronics -->db.products.find({ category: "electronics" }).pretty()
<!-- Find products cheaper than 30 -->db.products.find({ price: { $lt: 30 } }).pretty()
<!-- Find electronics cheaper than 100 -->db.products.find({ category: "electronics", price: { $lt: 100 } }).pretty()Two Minute Drill
- `find()` returns all matching documents, `findOne()` returns the first match.
- Use `pretty()` to format output nicely.
- Pass a query object to filter results: `{ field: value }`.
- Use projection to select specific fields: `{ field1: 1, field2: 1 }`.
- `countDocuments()` gives you the number of matching documents.
Need more clarification?
Drop us an email at career@quipoinfotech.com
