1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
===========
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**.
|