MongoDB - how can I access fields in a document?

To access fields in a MongoDB document, use the find() method with optional field projection to specify which fields to return. You can access all fields or select specific ones using projection syntax.

Syntax

// Access all fields
db.collection.find(query);

// Access specific fields using projection
db.collection.find(query, {field1: 1, field2: 1, _id: 0});

Sample Data

db.demo565.insertMany([
    {
        id: 101,
        Name: "David",
        CountryName: "US"
    },
    {
        id: 102,
        Name: "Carol",
        CountryName: "UK"
    },
    {
        id: 103,
        Name: "Sam",
        CountryName: "AUS"
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e90896739cfeaaf0b97b577"),
        ObjectId("5e90896839cfeaaf0b97b578"),
        ObjectId("5e90896839cfeaaf0b97b579")
    ]
}

Example 1: Access All Fields

db.demo565.find();
{ "_id": ObjectId("5e90896739cfeaaf0b97b577"), "id": 101, "Name": "David", "CountryName": "US" }
{ "_id": ObjectId("5e90896839cfeaaf0b97b578"), "id": 102, "Name": "Carol", "CountryName": "UK" }
{ "_id": ObjectId("5e90896839cfeaaf0b97b579"), "id": 103, "Name": "Sam", "CountryName": "AUS" }

Example 2: Access Specific Fields with Query

db.demo565.find({"Name": "Carol", "CountryName": "UK"}, {Name: 1});
{ "_id": ObjectId("5e90896839cfeaaf0b97b578"), "Name": "Carol" }

Key Points

  • {field: 1} includes the field in results (inclusion projection)
  • {field: 0} excludes the field from results (exclusion projection)
  • _id field is included by default unless explicitly excluded with {_id: 0}

Conclusion

Use find() with projection to access specific fields in MongoDB documents. Include fields with 1 or exclude with 0 to control which data is returned from your queries.

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

421 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements