MongoDB Project Fields
MongoDB Project Fields – In this MongoDB Tutorial, we shall learn to restrict only those fields to return in the result of a query.
In MongoDB Query Documents tutorial, we have learnt to filter MongoDB Documents based on a criteria, in which all the fields are returned in the result. But it is not always the case that we need all the fields in the result. We might be interested only on certain fields of the queried documents.
MongoDB projection is used to control the shape of the documents returned by a query. Instead of returning every field from every matching document, you can include only selected fields or exclude fields that are not needed by the application.
To limit the fields, we can make use of find() method. We can provide the required fields in a projection document and provide this projection document as second argument of find() method.
MongoDB find() Projection Syntax
Following is the syntax of find() method to accept projection document
db.collection.find(query_document, projection_document)
where projection_document is
{field1:projection_value, field1:projection_value, ..}
and projection_value can take 1 or 0.
| Projection_value | Description |
| 1 | Include the field:value in Result |
| 0 | Do not include the field:value in Result |
The projection document is not a filter condition. The first argument to find() decides which documents match the query. The second argument decides which fields from those matching documents are returned.
MongoDB Projection Rules for Include and Exclude Fields
MongoDB projection has one important rule: in the same projection document, you generally use either inclusion or exclusion, not both. The only common exception is the _id field, which is included by default and may be excluded with _id: 0 while including other fields.
| Projection type | Example | Meaning |
|---|---|---|
| Include selected fields | { name: 1, place: 1 } | Return only _id, name, and place. |
Include selected fields and remove _id | { name: 1, place: 1, _id: 0 } | Return only name and place. |
| Exclude selected fields | { phone: 0, address: 0 } | Return all fields except phone and address. |
If a projected field is not present in a document, MongoDB simply omits that field from that document in the result. Projection does not create empty fields for missing values.
Example – MongoDB Projection
Following is an example to limit fields in result using projection document.
Select Database.
> use tutorialkart
switched to db tutorialkart
Prepare projection document.
> projection_doc={"name":1,"place":1,_id:0}
{ "name" : 1, "place" : 1, "_id" : 0 }
When a projection document is provided, by default projection value of _id is 1. Change it to 0 if you do not require _id in the result. For rest of the fields you may set the projection value to 1, only for those required fields.
Query with projection document provided as second argument to find() method.
> db.people.find({},projection_doc)
{ "name" : "Midhuna", "place" : "Amaravati" }
{ "name" : "Akhil", "place" : "New York" }
{ "name" : "Honey" }
{ "name" : "Manju", "place" : "Vizag" }
{ "name" : "Bharat", "place" : "New York" }
{ "name" : "Arya" }
The result contains only those fields with respect to projection document.
MongoDB Projection with a Query Filter
Projection is often used along with a query filter. For example, you may want to find people from a specific place, but return only their names.
db.people.find(
{ place: "New York" },
{ name: 1, _id: 0 }
)
The first document { place: "New York" } filters the collection. The second document { name: 1, _id: 0 } returns only the name field from the matched documents.
{ "name" : "Akhil" }
{ "name" : "Bharat" }
Exclude Fields in MongoDB Query Results
When you want most fields but want to hide a few fields from the result, use exclusion projection with 0. This is useful when a collection has large or private fields that are not needed in a particular response.
db.people.find(
{},
{ phone: 0, address: 0 }
)
The query above returns all fields from each matching document except phone and address. Do not combine this style with inclusion fields such as { name: 1, phone: 0 }, except when excluding _id.
Project Nested Fields in MongoDB Documents
For embedded documents, use dot notation to project a nested field. For example, if each person document contains an address object, you can return only the city inside that object.
db.people.find(
{},
{ name: 1, "address.city": 1, _id: 0 }
)
This projection returns the name field and the nested address.city field. Other fields inside address, such as address.street or address.pin, are not returned.
Limit Array Fields with MongoDB Projection
Projection can also be used with array fields. If a document contains an array and you need only a part of that array, MongoDB supports projection operators such as $slice.
db.people.find(
{},
{ name: 1, scores: { $slice: 2 }, _id: 0 }
)
In this example, MongoDB returns the name field and only the first two elements of the scores array. This is helpful when an array can be large and the application needs only a preview.
MongoDB Projection in Node.js Driver Queries
In MongoDB drivers, the same idea is usually passed through an options object. For example, in the MongoDB Node.js driver, projection is provided inside the projection option.
const cursor = db.collection("people").find(
{ place: "New York" },
{ projection: { name: 1, place: 1, _id: 0 } }
);
The query filter is still the first argument. The projection is part of the options object, so the exact syntax can vary slightly between the MongoDB shell and application drivers.
Projection in find() and $project in Aggregation
The projection document used in find() is for selecting fields from query results. MongoDB also has an aggregation stage named $project, which is used inside an aggregation pipeline. The aggregation $project stage can also reshape documents, create computed fields, rename values, and apply expressions.
| Feature | Used with | Typical use |
|---|---|---|
find() projection | db.collection.find(query, projection) | Return only selected fields from matching documents. |
$project stage | db.collection.aggregate([...]) | Reshape documents inside an aggregation pipeline. |
Use find() projection for simple field selection. Use aggregation $project when you need computed fields or more advanced document transformation.
Common MongoDB Projection Mistakes
- Mixing inclusion and exclusion: Avoid using
1and0together in the same projection, except for excluding_id. - Forgetting that _id is included by default: Add
_id: 0when the ObjectId is not required in the result. - Confusing filter and projection: The first argument to
find()filters documents. The second argument controls returned fields. - Expecting missing fields to appear: If a field does not exist in a document, MongoDB does not add it to the returned document.
- Using projection as access control: Projection reduces returned data, but sensitive data should also be protected through proper schema design, validation, and application authorization.
QA Checklist for MongoDB Project Fields Tutorial
- Confirm that examples show projection as the second argument of
find(). - Check that inclusion examples use
1consistently and exclude only_idwith0. - Check that exclusion examples use
0consistently and do not mix normal include fields. - Verify that every output block matches the projected fields in the query above it.
- Confirm that nested field examples use quoted dot notation such as
"address.city".
FAQs on MongoDB Project Fields
What is projection in MongoDB?
Projection in MongoDB is the process of selecting which fields should be returned from matching documents. It is commonly provided as the second argument to the find() method.
How do I return only selected fields in MongoDB?
Pass a projection document with field values set to 1. For example, db.people.find({}, { name: 1, place: 1, _id: 0 }) returns only name and place.
Why does MongoDB return _id even when I project other fields?
The _id field is included by default in MongoDB query results. To remove it from the result, explicitly add _id: 0 in the projection document.
Can I use both 1 and 0 in the same MongoDB projection?
Do not mix inclusion and exclusion in the same projection document, except for the common case of excluding _id. For example, { name: 1, _id: 0 } is valid.
How do I project nested fields in MongoDB?
Use dot notation inside the projection document. For example, { "address.city": 1, _id: 0 } returns only the nested city field from the address document.
Conclusion
In this MongoDB Tutorial, we have learnt to limit the fields in the result using projection document as second argument to find() method.
Use inclusion projection when you need a small set of fields, exclusion projection when you need almost every field except a few, and _id: 0 when the default ObjectId field should not appear in the query result.
TutorialKart.com