MongoDB find() method Tutorial

The MongoDB find() method is a query opetation method to retrieve documents from a collection.

Basic Document Retrieval

MongoDB find() method is used to retrieve all documents in a collection.

db.myCollection.find();
        

Limit the Number of Results

The limit() to restrict the number of documents returned.

db.myCollection.find().limit(5);
        

Filtering by Field

Specify the filter criteria within the find() method to match documents.

db.myCollection.find({ age: 25 });
        

Logical Operators

Use $and, $or, and other logical operators for complex queries.

db.myCollection.find({ $or: [{ age: 25 }, { name: "Alice" }] });
        

Projection

The projection to limit the fields returned in the result.

db.myCollection.find({}, { name: 1, age: 1, _id: 0 });
        

Sorting Results

We can sort MongoDB documents using sort(), specifying fields and order.

db.myCollection.find().sort({ age: 1 }); // Ascending order
        

Counting Documents

The count() to get the number of matching documents.

db.myCollection.find({ age: 30 }).count();
        

Limit Fields in Result

The MongoDB findOne() to retrieve the first matching document.

db.myCollection.findOne({ age: 30 }, { name: 1, age: 1, _id: 0 });
        

Regular Expressions

The regex for pattern-based searches in field values.

db.myCollection.find({ name: /^J/ }); // Names starting with 'J'
        

Nested Document Search

Search within nested documents or arrays using dot notation.

db.myCollection.find({ "address.city": "New York" });