Query and View Documents
After inserting data, you will want to retrieve and view it. The primary method for querying a collection is find().
To view all documents in the products collection, run the find() method without any arguments.
db.products.find();
The mongosh shell automatically formats the output for readability, displaying all three documents in your collection.
[
{
_id: ObjectId("..."),
name: 'Laptop',
price: 1200,
category: 'Electronics'
},
{
_id: ObjectId("..."),
name: 'Keyboard',
price: 75,
category: 'Electronics'
},
{
_id: ObjectId("..."),
name: 'Desk Chair',
price: 150,
category: 'Furniture'
}
]
The find() method can also accept a query document to filter the results. This allows you to find documents that match specific criteria. For example, let's find all products in the "Electronics" category.
db.products.find({ category: "Electronics" });
This command will return only the documents where the category field has the value "Electronics".
[
{
_id: ObjectId("..."),
name: 'Laptop',
price: 1200,
category: 'Electronics'
},
{
_id: ObjectId("..."),
name: 'Keyboard',
price: 75,
category: 'Electronics'
}
]
This simple filtering capability is a powerful feature for retrieving specific data from your collections.