Skip to content

Commit a79831a

Browse files
(DOCSP-7598): Find a Document Usage Example (#4)
1 parent 55eec9a commit a79831a

File tree

3 files changed

+62
-0
lines changed

3 files changed

+62
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
const { MongoClient } = require('mongodb');
3+
4+
5+
const client = new MongoClient(
6+
'mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&w=majority',
7+
);
8+
9+
async function run() {
10+
try {
11+
await client.connect();
12+
13+
const database = client.db('sample_mflix');
14+
const collection = database.collection('movies');
15+
16+
// create a query document to look up an exact match for a move with this title
17+
const query = { title: 'The Room' };
18+
const movie = await collection.findOne(query);
19+
// since this method returns the matched document, not a cursor, print it directly
20+
console.log(movie);
21+
} finally {
22+
await client.close();
23+
}
24+
}
25+
run().catch(console.dir);

source/usage-examples.txt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,9 @@ Usage Examples
44

55
.. default-domain:: mongodb
66

7+
:doc:`findOne </usage-examples/findOne>`
8+
9+
.. toctree::
10+
:caption: Examples
11+
12+
/usage-examples/findOne

source/usage-examples/findOne.rst

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
===============
2+
Find a Document
3+
===============
4+
5+
.. default-domain:: mongodb
6+
7+
Overview
8+
--------
9+
10+
You can find a single document using the
11+
`collection.findOne() <https://mongodb.github.io/node-mongodb-native/3.3/api/Collection.html#findOne>`_
12+
method. ``findOne`` takes an optional query document, an optional sort
13+
order, and an optional projection. ``findOne`` returns a
14+
`Promise <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise>`_
15+
that resolves
16+
to the first document matching the query in the specified sort order,
17+
which defaults to
18+
`natural sort order <https://docs.mongodb.com/manual/reference/glossary/#term-natural-order>`_.
19+
If no document matches the query, ``findOne`` returns a Promise that
20+
resolves to ``null``. Since ``findOne`` returns only one document, the
21+
Promise returned by this method resolves to an
22+
`Object <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object>`_,
23+
not a
24+
`Cursor <https://mongodb.github.io/node-mongodb-native/3.3/api/Cursor.html>`_.
25+
26+
The following snippet finds a single document from the ``movies``
27+
collection:
28+
29+
.. literalinclude:: /code-snippets/usage-examples/findOne.js
30+
:language: javascript
31+
:emphasize-lines: 17

0 commit comments

Comments
 (0)