Forward Advance Learning

Formatting results with projection

Find takes a second parameter which allows you to whitelist fields to pass into the output document. We call this projection.

You can choose fields to pass though. If we have a collection containing two documents like so:

{
ham: 4,
eggs: 2
}
{
cheese: 6,
lime: 0.5
}

Then we write a finder like this:

db.breakfast.find({}, {
eggs: true,
lime: true
})

This will yield a collection like so:

{
eggs: 2
},
{
lime: 0.5
}

Exercise - Tidy up your output

  • Use projection to format your array of people. We want only the names.
  • Output just the names of the people who are 99 years old
  • Output only the cats, like this:
{ "cat" : { "name" : "Fluffy Frank", "age" : 13 } }

When you output the cats, you will need to find only people who have cats, where cats $exists, or you will have gaps in your data.

Excluding the id field

You will notice that the ID field is always passed through project by default. This is often desirable, but you may wish to hide it, perhaps to conceal your implementation, or to keep your communication over the wire tight.

You can do this easily by passing _id: false:

db.breakfast.find({}, {
eggs: true,
lime: true,
_id: false
})

Exercise - remove the ids

  • List the cats. Remove the ids from the output.