Using field projection MongoDB

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In our last tutorial which we continue from, we found all states starting with the letter A.  And we simply display the state names.  We actually did not need all the fields in record.  Field projection lets use tell mongodb which fields return and which fields to not return.

We modify our previous code to add a projection to our find() method …

mongodb field projections

mongodb field projections

The projection tell mongodb that we just are interested in the “state” field.   The rest of the field will not be returned.  Except for the _id field which will be returned by default regardless unless you explicitly tell it not to by using a projection like this…

var projection = { ‘state’ : 1, ‘_id’ : 0 }

This app will output exactly the same result as in our previous tutorial…

console output

console output

If you also need the “high” temperature field, you can use the projection …

var projection = { ‘state’ : 1, ‘_id’ : 0, ‘high’ : 1 }

Error: You cannot currently mix including and excluding fields.

However, for the other fields that you don’t need, you should not put zero.  Because if you do the following where “state” is 1 and “high” is 0 such as …

var projection = { ‘state’ : 1, ‘_id’ : 0, ‘high’ : 0 }

mongodb will throw an error saying …

“You cannot currently mix including and excluding fields.”

This was in May 2014 when I was using mongodb module 1.4.0 connecting to mongolab.  Perhaps this will change in the future.