===========
Projections
===========

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 projection 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 fields and has the
following form:

.. code-block:: js

   { 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
which 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:: js

   const { MongoClient } = require('mongodb');
   
   // Connection URL
   const url = 'mongodb://localhost:27017';
   
   // Database Name
   const dbName = 'myproject';
   
   // Create a new MongoClient
   const client = new MongoClient(url);

   async function main(connect) {
     const collection = client.db(dbName).collection('restaurants');

     const docs = await collection
       .find({ cuisine : 'Brazilian' })
       .project({ name : 1, cuisine : 1 })
       .toArray();
       
     console.log("Found the following records");
     console.log(docs);
   }

   // Function to connect to the server and run your code
   async function run() {
     try {
       // Connect the client to the server
       await client.connect();
       console.log('Connected successfully to server');

       await main(client);
     } finally {
       // Ensures that the client will close when you finish/error
       await client.close();
     }
   }

   // Runs your code
   run();

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

.. code-block:: js

   { name : 1, cuisine : 1, _id: 0 }

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

.. code-block:: js

   { address : 0 }

.. warning::
   Both the MongoDB shell and the 2.x version of the Node driver supported
   a syntax that allowed users to pass a projection as a second argument
   to the find call: 
   
     ``collection.find({ cuisine : 'Brazilian' }, { name : 1, cuisine : 1 })``.
   
   **This syntax is not supported in the 3.x version of the driver**.