Projecting Nested and Array Fields
Learners will use dot notation and the $slice operator to project parts of arrays and nested sub-documents.
Projecting Nested Fields With Dot Notation
To project a specific field from an embedded sub-document, use dot notation in the projection key. For example, if a document has an address sub-document, you can project only address.city without returning the full address object. MongoDB traverses the nested path and returns only the specified leaf field, keeping the parent field wrapper in the result.
// Document shape: { name, address: { street, city, zip }, email }
const user = await db.collection('users').findOne(
{ email: 'alice@example.com' },
{ projection: { name: 1, 'address.city': 1, _id: 0 } }
);
// Result: { name: 'Alice', address: { city: 'Austin' } }
// street and zip are excluded; only city is returned inside addressExcluding Nested Fields
Just as with top-level fields, you can exclude specific nested fields while returning the rest of the sub-document. Using 'address.zip': 0 returns the entire address object except the zip field. This is useful for hiding internal-use sub-fields while exposing the rest of a nested object to the client.
// Return everything except address.zip
const user = await db.collection('users').findOne(
{ email: 'alice@example.com' },
{ projection: { 'address.zip': 0, passwordHash: 0 } }
);
// Result includes address.street and address.city but not address.zipAll lessons in this course
- Inclusion vs Exclusion Projections
- Projecting Nested and Array Fields
- The $ and $elemMatch Array Projections
- Projection Best Practices for API Responses