File tree Expand file tree Collapse file tree 3 files changed +62
-0
lines changed
code-snippets/usage-examples Expand file tree Collapse file tree 3 files changed +62
-0
lines changed Original file line number Diff line number Diff line change
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 ) ;
Original file line number Diff line number Diff line change @@ -4,3 +4,9 @@ Usage Examples
4
4
5
5
.. default-domain:: mongodb
6
6
7
+ :doc:`findOne </usage-examples/findOne>`
8
+
9
+ .. toctree::
10
+ :caption: Examples
11
+
12
+ /usage-examples/findOne
Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments