Before querying data, ensure you are using the correct database.
use myDatabase
To fetch all documents from a collection, use find().
db.users.find()
For a more readable output:
db.users.find().pretty()
To find documents that match a specific condition, pass a query inside find().
db.users.find({ age: 30 })
If you only need one document, use findOne().
db.users.findOne({ city: "New York" })
You can control which fields to display by passing a second argument to find().
db.users.find({}, { name: 1, city: 1, _id: 0 })
MongoDB allows advanced queries using comparison operators like $gt, $lt, $eq, etc.
db.users.find({ age: { $gt: 25 } })
To sort results in ascending (1) or descending (-1) order, use sort().
db.users.find().sort({ age: 1 }) # Ascending
db.users.find().sort({ age: -1 }) # Descending
limit() to control the number of documents retrieved.skip() to ignore a specific number of documents.db.users.find().limit(5) # Fetches only 5 documents
db.users.find().skip(2) # Skips the first 2 documents
You’ve now learned how to retrieve data from MongoDB efficiently. Here’s a quick recap:
✅ Use find() to retrieve all documents.
✅ Use findOne() for a single document.
✅ Use filters and comparison operators to refine results.
✅ Use sort(), limit(), and skip() for better control.
Now, start querying data effectively in MongoDB! 🚀