Projection in MongoDB

Projection in MongoDB

Projection in mongoDB means to select the nessacery fields instead of all the fields.

RDBMS example of projection

In RDBMS to use projection we define the column that we need instead of "*".

select id, name from yamicode;

Projection in MongoDB

The projection method takes as parameter a JSON object that takes as key the name of the field and as a value either 0 (hide) or 1 (show)

Inclusion: Getting the field name and types from MongoDB projection

> db.test.find({}, {name: 1, types: 1})

exclusion: Removing the field name and types from MongoDB projection

> db.test.find({}, {name: 0, types: 0})

Removing _id from inclusion in MongoDB projection

> db.test.find({}, {name: 1, types: 1, _id: 0})

Except for the _id you can't mix inclusion (1) and exclusion (0) in the same query. You have only two choices either you planning on hiding or showing fields it depends on your case. The _id field can take a 0 in an inclusion projection because it's added by default to the inclusion projection

Working with arrays and Embedded Documents in MongoDB

Return Specific Fields in Embedded Documents

You can return specific fields in an embedded document. Use the dot notation to refer to the embedded field and set to 1 in the projection document.

Document example

{ 
	"_id" : ObjectId("5e2f446bf098cf25b5b434c6"), 
	"name" : "something", 
	"address" : {
		city: "Paris",
		country: "France"
	}
}

Projection using the dot notation

db.collection.find({}, {"address.city": 1, _id: 0})
Result
{ "address" : { "city" : "Paris" } }

Projection on Embedded Documents in an Array

Use dot notation to project specific fields inside documents embedded in an array.

Document example

{ 
	"_id" : ObjectId("5e2f446bf098cf25b5b434c6"), 
	"name" : "something", 
	"addresses" : [{
		city: "Paris",
		country: "France"
	},
	{
		city: "London",
		country: "UK"
	}]
}

Projection using the dot notation

db.collection.find({}, {"address.city": 1, _id: 0})
Result
{ "addresses" : [ { "city" : "Paris" }, { "city" : "London" } ] }