The find() command in MongoDB is used to query documents within a collection. It retrieves documents that match specified criteria and returns them as a cursor, which can be iterated over to access the results.
Basic Syntax
db.collectionName.find(query, projection)
query: A document that specifies the selection criteria. It can include conditions to filter the documents.projection: An optional document that specifies which fields to include or exclude in the returned documents.
Example Usage
-
Find All Documents:
To retrieve all documents in a collection:db.collectionName.find() -
Find Documents with Criteria:
To find documents that match specific criteria, such as documents where theagefield is greater than 25:db.collectionName.find({ age: { $gt: 25 } }) -
Projection:
To return only specific fields, such asnameandage, while excluding others:db.collectionName.find({}, { name: 1, age: 1 }) -
Chaining Methods:
You can chain methods to further refine your query. For example, to sort the results byagein ascending order:db.collectionName.find().sort({ age: 1 }) -
Limit Results:
To limit the number of documents returned:db.collectionName.find().limit(5)
Cursor
The result of the find() command is a cursor, which allows you to iterate through the results. You can convert the cursor to an array using the toArray() method:
const results = await db.collectionName.find().toArray();
console.log(results);
Summary
The find() command is a powerful tool for querying documents in MongoDB, allowing for flexible and complex queries to retrieve the data you need from your collections.
