MongoDB - Projection Queries

A projection query is a query where you specify which fields should be returned.

In MongoDB, when you query a collection using the db.collection.find() method, you can specify which fields you would like to have returned.

You can do this by including the field names in your query, and adding a 1 or 0 next to them, to specify whether it should be returned or not. This is a projection parameter. A projection parameter of 1 will display the field and a 0 will hide it.

Example

First let's do a query without projection (so we can see how many fields are returned):

Without Projection

Result:


{ "_id" : 1, "name" : "Ian Gillan", "instrument" : "Vocals" }

{ "_id" : 6, "name" : "Jeff Martin", "instrument" : "Vocals", "born" : 1969 }

With Projection

Now, let's use projection to display just the name field:

Result:


{ "_id" : 1, "name" : "Ian Gillan" }

{ "_id" : 6, "name" : "Jeff Martin" }

You will notice that the _id field is automatically included, even if you don't specify it. You can exclude this field by using a 0 against it:

Result:


{ "name" : "Ian Gillan" }

{ "name" : "Jeff Martin" }

Mixing Inclusions and Exclusions

You can't mix 1s and 0s (with the exception of the _id field). If you try to mix inclusions and exclusions, like this:

You'll end up with this error:


Error: error: {

	"waitedMS" : NumberLong(0),

	"ok" : 0,

	"errmsg" : "Projection cannot have a mix of inclusion and exclusion.",

	"code" : 2

}

So to you either include fields or exclude them — not both.

Here's an example of specifying fields by exclusion:

Result:


{ "name" : "Ian Gillan" }

{ "name" : "Jeff Martin", "born" : 1969 }