How do I display a list of objects based on a specific property with MongoDB?

To display a list of objects based on a specific property in MongoDB, use dot notation in the find() method to query nested object properties or array elements.

Syntax

db.collection.find({"object.property": value});
db.collection.find({"object.array.property": value});

Sample Data

Let us create a collection with student documents ?

db.demo455.insertMany([
    {"Information": {"Student": [{"Name": "Chris", "Age": 22}]}},
    {"Information": {"Student": [{"Name": "David", "Age": 21}]}},
    {"Information": {"Student": [{"Name": "Bob", "Age": 24}]}},
    {"Information": {"Student": [{"Name": "Robert", "Age": 21}]}}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e7e1876dbcb9adb296c95c5"),
        ObjectId("5e7e1883dbcb9adb296c95c6"),
        ObjectId("5e7e188adbcb9adb296c95c7"),
        ObjectId("5e7e18bcdbcb9adb296c95c8")
    ]
}

Display All Documents

db.demo455.find();
{"_id": ObjectId("5e7e1876dbcb9adb296c95c5"), "Information": {"Student": [{"Name": "Chris", "Age": 22}]}}
{"_id": ObjectId("5e7e1883dbcb9adb296c95c6"), "Information": {"Student": [{"Name": "David", "Age": 21}]}}
{"_id": ObjectId("5e7e188adbcb9adb296c95c7"), "Information": {"Student": [{"Name": "Bob", "Age": 24}]}}
{"_id": ObjectId("5e7e18bcdbcb9adb296c95c8"), "Information": {"Student": [{"Name": "Robert", "Age": 21}]}}

Example: Query by Specific Property

Find all students with Age equal to 21 ?

db.demo455.find({"Information.Student.Age": 21});
{"_id": ObjectId("5e7e1883dbcb9adb296c95c6"), "Information": {"Student": [{"Name": "David", "Age": 21}]}}
{"_id": ObjectId("5e7e18bcdbcb9adb296c95c8"), "Information": {"Student": [{"Name": "Robert", "Age": 21}]}}

Key Points

  • Use dot notation to access nested object properties: "object.property"
  • For arrays containing objects, use: "array.property" to match any element in the array
  • MongoDB automatically searches through array elements when using dot notation

Conclusion

Dot notation allows querying nested objects and array elements efficiently. Use find({"path.to.property": value}) to filter documents based on specific nested properties in MongoDB collections.

Updated on: 2026-03-15T03:02:19+05:30

386 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements