diff --git a/source/crud/query/find.txt b/source/crud/query/find.txt index e51ae9b5..32f2ada3 100644 --- a/source/crud/query/find.txt +++ b/source/crud/query/find.txt @@ -53,6 +53,36 @@ collection. To learn more about query filters, see the :ref:`kotlin-sync-specify-query` guide. +Find One Document Example +~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example chains the ``first()`` method to the ``find()`` method call to find +the first document in which the value of the ``cuisine`` field is ``"Spanish"``: + +.. literalinclude:: /includes/read/retrieve.kt + :start-after: start-find-one + :end-before: end-find-one + :language: kotlin + :copyable: + :dedent: + +The ``find()`` operation in the preceding example returns a MongoDB document, which you +can print, as shown in the following example: + +.. io-code-block:: + :copyable: true + + .. input:: /includes/read/retrieve.kt + :start-after: start-find-one-print + :end-before: end-find-one-print + :language: kotlin + :dedent: + + .. output:: + :visible: false + + Restaurant(name=Tropicoso Club, cuisine=Spanish) + Find Documents Example ~~~~~~~~~~~~~~~~~~~~~~ @@ -124,6 +154,13 @@ modifying queries: - | Specifies a string to attach to the query. This can help you trace and interpret the operation in the server logs and in profile data. + * - ``first()`` + - | Returns the first document that matches the query or throws a ``MongoClientException`` + if no matching documents exist. + + * - ``firstOrNull()`` + - | Returns the first document that matches the query or ``null`` if no matching documents exist. + * - ``hint()`` - | Specifies the index to use for the query. diff --git a/source/includes/read/retrieve.kt b/source/includes/read/retrieve.kt index 6a9df06c..e7774ae2 100644 --- a/source/includes/read/retrieve.kt +++ b/source/includes/read/retrieve.kt @@ -26,6 +26,10 @@ fun main() { val results = collection.find(eq(Restaurant::cuisine.name, "Spanish")) // end-find + // start-find-one + val results = collection.find(eq(Restaurant::cuisine.name, "Spanish")).first() + // end-find-one + // start-find-iterate val results = collection.find(eq(Restaurant::cuisine.name, "Spanish")) results.forEach { result -> @@ -33,6 +37,11 @@ fun main() { } // end-find-iterate + // start-find-one-print + val results = collection.find(eq(Restaurant::cuisine.name, "Spanish")).first() + println(results) + // end-find-one-print + // start-find-all val results = collection.find() // end-find-all