Skip to content

Commit d56dcd3

Browse files
authored
DOCSP-51326-add-find-one (#114)
* add find one * fix code * edit code * add table entries * formatting * monospace * mw feedback
1 parent 546c88e commit d56dcd3

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

source/crud/query/find.txt

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,36 @@ collection.
5353

5454
To learn more about query filters, see the :ref:`kotlin-sync-specify-query` guide.
5555

56+
Find One Document Example
57+
~~~~~~~~~~~~~~~~~~~~~~~~~
58+
59+
The following example chains the ``first()`` method to the ``find()`` method call to find
60+
the first document in which the value of the ``cuisine`` field is ``"Spanish"``:
61+
62+
.. literalinclude:: /includes/read/retrieve.kt
63+
:start-after: start-find-one
64+
:end-before: end-find-one
65+
:language: kotlin
66+
:copyable:
67+
:dedent:
68+
69+
The ``find()`` operation in the preceding example returns a MongoDB document, which you
70+
can print, as shown in the following example:
71+
72+
.. io-code-block::
73+
:copyable: true
74+
75+
.. input:: /includes/read/retrieve.kt
76+
:start-after: start-find-one-print
77+
:end-before: end-find-one-print
78+
:language: kotlin
79+
:dedent:
80+
81+
.. output::
82+
:visible: false
83+
84+
Restaurant(name=Tropicoso Club, cuisine=Spanish)
85+
5686
Find Documents Example
5787
~~~~~~~~~~~~~~~~~~~~~~
5888

@@ -124,6 +154,13 @@ modifying queries:
124154
- | Specifies a string to attach to the query. This can help you trace and interpret the
125155
operation in the server logs and in profile data.
126156

157+
* - ``first()``
158+
- | Returns the first document that matches the query or throws a ``MongoClientException``
159+
if no matching documents exist.
160+
161+
* - ``firstOrNull()``
162+
- | Returns the first document that matches the query or ``null`` if no matching documents exist.
163+
127164
* - ``hint()``
128165
- | Specifies the index to use for the query.
129166

source/includes/read/retrieve.kt

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,22 @@ fun main() {
2626
val results = collection.find(eq(Restaurant::cuisine.name, "Spanish"))
2727
// end-find
2828

29+
// start-find-one
30+
val results = collection.find(eq(Restaurant::cuisine.name, "Spanish")).first()
31+
// end-find-one
32+
2933
// start-find-iterate
3034
val results = collection.find(eq(Restaurant::cuisine.name, "Spanish"))
3135
results.forEach { result ->
3236
println(result)
3337
}
3438
// end-find-iterate
3539

40+
// start-find-one-print
41+
val results = collection.find(eq(Restaurant::cuisine.name, "Spanish")).first()
42+
println(results)
43+
// end-find-one-print
44+
3645
// start-find-all
3746
val results = collection.find()
3847
// end-find-all

0 commit comments

Comments
 (0)