0
0
MongoDBquery~5 mins

find method basics in MongoDB

Choose your learning style9 modes available
Introduction

The find method helps you look for data inside a collection. It shows you all the items that match what you want.

You want to see all the books by a certain author in your library database.
You need to find all customers who live in a specific city.
You want to check which products cost less than $20 in your store.
You want to list all orders made on a certain date.
Syntax
MongoDB
db.collection.find(query, projection)

query is what you want to search for. If empty, it shows all items.

projection decides which fields to show or hide in the results.

Examples
Finds all books where the author is Jane Austen.
MongoDB
db.books.find({author: "Jane Austen"})
Finds customers in New York and shows only their name and city.
MongoDB
db.customers.find({city: "New York"}, {name: 1, city: 1, _id: 0})
Finds products with price less than 20.
MongoDB
db.products.find({price: {$lt: 20}})
Sample Program

This example adds three students to the collection. Then it finds all students who study Math and prints their details.

MongoDB
db.students.insertMany([
  {name: "Alice", age: 20, major: "Math"},
  {name: "Bob", age: 22, major: "History"},
  {name: "Carol", age: 20, major: "Math"}
])

// Find all students majoring in Math
const results = db.students.find({major: "Math"})
results.forEach(doc => printjson(doc))
OutputSuccess
Important Notes

If you leave the query empty like {}, it returns all documents in the collection.

The find method returns a cursor, so you can loop through results or convert them to an array.

Summary

The find method searches for documents matching your query.

You can choose which fields to show using projection.

It returns a cursor to access the matching documents.