Introduction
Learn how to query documents from a MongoDB collection using the mongosh shell interface.
Connecting to MongoDB
Before querying documents, ensure you are connected to your MongoDB server:
Example: Connecting to MongoDB
mongoshThis command starts the mongosh shell and connects to the default MongoDB server running locally.
Switching to a Database
Switch to the database where your collection resides using the use command:
Example: Switching to a Database
use mydatabaseThis command switches to the “mydatabase” database. Replace mydatabase with your database name.
Querying Documents
To query documents from a MongoDB collection, use the find method:
Example: Basic Query
db.mycollection.find()This command retrieves all documents from the mycollection collection.
You can also specify query criteria to filter documents:
Example: Query with Filter
db.mycollection.find({ status: "active" })This command retrieves documents from mycollection where the status field equals “active”.
Projection
Limit the fields returned using projection:
Example: Projection
db.mycollection.find({}, { name: 1, age: 1 })This command retrieves documents from mycollection and includes only the name and age fields.
Sorting
Sort query results:
Example: Sorting
db.mycollection.find().sort({ age: 1 })This command retrieves documents from mycollection and sorts them in ascending order based on the age field.
Limit and Skip
Limit and skip query results:
Example: Limit and Skip
db.mycollection.find().limit(10).skip(5)This command retrieves up to 10 documents from mycollection, skipping the first 5.
Conclusion
Querying documents from a MongoDB collection using mongosh provides powerful capabilities for retrieving and manipulating data. Experiment with different query options to suit your specific requirements.