How to get items with a specific value from documents using MongoDB shell?

To get documents with a specific field value in MongoDB, use the find() method with a query filter. This allows you to retrieve only the documents that match your specified criteria.

Syntax

db.collection.find(
    { "field": "value" },
    { "field1": 1, "field2": 1 }
)

The first parameter is the query filter, and the second optional parameter is the projection to specify which fields to include or exclude.

Sample Data

db.demo563.insertMany([
    { "Name": "Chris", "Age": 21, "isMarried": true },
    { "Name": "Bob", "Age": 23, "isMarried": false },
    { "Name": "Carol", "Age": 23, "isMarried": true },
    { "Name": "Mike", "Age": 21, "isMarried": true }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e8f546c54b4472ed3e8e878"),
        ObjectId("5e8f547854b4472ed3e8e879"),
        ObjectId("5e8f548b54b4472ed3e8e87a"),
        ObjectId("5e8f549454b4472ed3e8e87b")
    ]
}

Example: Find Documents with Specific Age

To get all documents where Age is 21 ?

db.demo563.find({ "Age": 21 });
{ "_id": ObjectId("5e8f546c54b4472ed3e8e878"), "Name": "Chris", "Age": 21, "isMarried": true }
{ "_id": ObjectId("5e8f549454b4472ed3e8e87b"), "Name": "Mike", "Age": 21, "isMarried": true }

With Field Projection

To get documents with Age 21 but show only specific fields ?

db.demo563.find(
    { "Age": 21 },
    { "Name": 1, "Age": 1, "isMarried": 1 }
);
{ "_id": ObjectId("5e8f546c54b4472ed3e8e878"), "Name": "Chris", "Age": 21, "isMarried": true }
{ "_id": ObjectId("5e8f549454b4472ed3e8e87b"), "Name": "Mike", "Age": 21, "isMarried": true }

Key Points

  • The find() method accepts a query filter as the first parameter to match specific field values.
  • Use projection (second parameter) to control which fields are returned in the results.
  • Field projection uses 1 to include fields and 0 to exclude them.

Conclusion

Use db.collection.find({"field": "value"}) to retrieve documents matching specific criteria. Combine with projection to control which fields are displayed in the results.

Updated on: 2026-03-15T03:35:26+05:30

510 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements