mongodb/mongo-ruby-driver

View on GitHub
docs/reference/projection.txt

Summary

Maintainability
Test Coverage
**********
Projection
**********

.. default-domain:: mongodb

.. contents:: On this page
   :local:
   :backlinks: none
   :depth: 1
   :class: singlecol

By default, queries in MongoDB return all fields in matching
documents. To limit the amount of data that MongoDB sends to
applications, you can include a 
:manual:`projection</tutorial/project-fields-from-query-results/>`
document in the query operation.

Projection Document
===================

The projection document limits the fields to return for all
matching documents. The projection document can specify the
inclusion of fields or the exclusion of field and has the
following form:

.. code-block:: javascript

  { 'projection': { field1: <value>, field2: <value> ... } }

``<value>`` may be ``0`` (or ``false``) to exclude the field, or
``1`` (or ``true``) to include it. With the exception of the ``_id``
field, you may not have both inclusions and exclusions in the same
projection document.

Examples
========

The following code example uses the ``restaurants`` sample dataset.

To return only the ``name``, ``cuisine`` and ``_id`` fields for
documents that match the query filter, explicitly include the ``name``
and ``cuisine`` fields in the projection document. The ``_id`` field is
included automatically unless specifically excluded.

.. code-block:: ruby

  client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test')
  collection = client[:restaurants]

  collection.find({}, { 'projection' =>
    { 'name' => 1, 'cuisine' => 1 } }).limit(5).each do |doc|
    p doc
  end

To return ``name`` and ``cuisine`` but exclude all other fields,
including ``_id``, use the following projection document:

.. code-block:: javascript

  { 'projection' => { 'name' => 1, 'cuisine' => 1, '_id' => 0 } }


To return all fields *except* the address field, use the following:

.. code-block:: javascript

  { 'projection' => { 'address' => 0 } }