MongoDB Projection

MongoDB Projection

In this tutorial, we will learn another interesting topic of MongoDB which is MongoDB Projection. This is used when we want to get the selected fields of the documents rather than all fields.

For example, we have a collection where we have stored documents that have the fields: dept_id, employeeName but we want to see only the dept_id of all the department then in that case we can use projection to get only the dept_id.

Syntax:

db.collection_name.find({},{field_key:1 or 0})

We have a collection named department that has following documents.

db.department.find()
{ "_id" : ObjectId("5b3725145eb29c373ddadd52"), "dept_id" : 3, "name" : "Production" }
{ "_id" : ObjectId("5b3bcdb46728a1b55ecec860"), "dept_id" : 4, "name" : "Sales" }
{ "_id" : ObjectId("5b3bced56728a1b55ecec862"), "dept_id" : 5, "name" : "Pre-Sales" }

To get only the ‘name’ for all the documents, we will use the Projection like this:

db.department.find({}, {"_id": 0, "name": 1})
{ "name" : "Production" }
{ "name" : "Sales" }
{ "name" : "Pre-Sales" }

Note : Value 1 means show that field and 0 means do not show that field. When we set a field to 1 in Projection other fields are automatically set to 0, except _id, so to avoid the _id we need to specifically set it to
0 in projection. The vice versa is also true when we set few fields to 0, other fields set to 1 automatically(see the below example)

Another way of doing the same thing:

db.department.find({}, {"_id": 0, "dept_id": 0})
{ "name" : "Production" }
{ "name" : "Sales" }
{ "name" : "Pre-Sales" }

Important Note:

Some of you may get error while using Projection in Query:

db.department.find({}, {"_id": 0, "dept_id": 0, "name":1})
Error: error: {
        "ok" : 0,
        "errmsg" : "Projection cannot have a mix of inclusion and exclusion.",
        "code" : 2,
        "codeName" : "BadValue"
    }

This happens when you set some fields to 0 and other to 1, in other words you mix inclusion and exclusion, the only exception is the _id field. for example: The following Query would produce this error:

This is because we have set dept_id to 1 and other field name to 1. We can’t mix these. You either set those fields that you don’t want to display to 0 or set the fields to 1 that you want to display.

Leave a Reply

Your email address will not be published. Required fields are marked *