skip to content
Alvin Lucillo

MongoDB Projection

/ 1 min read

💻 Tech

MongoDB Project allows inclusion and exclusion of fields from the documents returned by the query.

For example, we have these documents in a collection:

[
  {
    "emp_id": 1,
    "dept_id": 1,
    "salary": 100,
    "first_name": "Fizz",
    "last_name": "Buzz"
  },
  {
    "emp_id": 2,
    "dept_id": 1,
    "salary": 200,
    "first_name": "Jack",
    "last_name": "Jill"
  },
  {
    "emp_id": 3,
    "dept_id": 2,
    "salary": 300,
    "first_name": "Jane",
    "last_name": "Doe"
  }
]

Setting a field to 1 and 0 includes and excludes fields from the query result respectively.

db.collection.find({
  "dept_id": 1
},
{
  "emp_id": 0
})

Result:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "dept_id": 1,
    "first_name": "Fizz",
    "last_name": "Buzz",
    "salary": 100
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "dept_id": 1,
    "first_name": "Jack",
    "last_name": "Jill",
    "salary": 200
  }
]

Another example is data transformation. You can use operators like $concat. In the example below, the operator concatenates the first and last name.

db.collection.aggregate([
  {
    "$project": {
      "full_name": {
        "$concat": [
          "$first_name",
          " ",
          "$last_name"
        ]
      }
    }
  }
])

Result:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "full_name": "Fizz Buzz"
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "full_name": "Jack Jill"
  },
  {
    "_id": ObjectId("5a934e000102030405000002"),
    "full_name": "Jane Doe"
  }
]