Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions source/includes/read/specify-a-query.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package org.example
import com.mongodb.ConnectionString
import com.mongodb.MongoClientSettings
import com.mongodb.client.model.Filters.*
import com.mongodb.kotlin.client.MongoClient
import org.bson.codecs.pojo.annotations.BsonId

// start-data-class
data class Fruit(
@BsonId
val id: Int,
val name: String,
val quantity: Int,
val rating: Int,
val color: String,
val type: List<String>
)
// end-data-class

fun main() {
// start-sample-data
val uri = "<connection string URI>"

val settings = MongoClientSettings.builder()
.applyConnectionString(ConnectionString(uri))
.retryWrites(true)
.build()

val mongoClient = MongoClient.create(settings)
val database = mongoClient.getDatabase("sample_fruit")
val collection = database.getCollection<Fruit>("fruits")

collection.insertMany(listOf(
Fruit(1, "apples", 5, 3, "red", listOf("fuji", "honeycrisp")),
Fruit(2, "bananas", 7, 4, "yellow", listOf("cavendish")),
Fruit(3, "oranges", 6, 2, null, listOf("naval", "mandarin")),
Fruit(4, "pineapples", 3, 5, "yellow", null)
))
// end-sample-data

// start-find-exact
val results = collection.find(eq(Fruit::color.name, "yellow"))

results.forEach { result ->
println(result);
}
// end-find-exact

// start-find-comparison
val results = collection.find(gt(Fruit::rating.name, 2))

results.forEach { result ->
println(result)
}
// end-find-comparison

// start-find-logical
val results = collection.find(
or(
gt(Fruit::quantity.name, 5),
eq(Fruit::color.name, "yellow")
)
)

results.forEach { result ->
println(result)
}
// end-find-logical

// start-find-array
val results = collection.find(size(Fruit::type.name, 2))

results.forEach { result ->
println(result)
}
// end-find-array

// start-find-element
val results = collection.find(exists(Fruit::color.name))

results.forEach { result ->
println(result)
}
// end-find-element

// start-find-evaluation
val results = collection.find(regex(Fruit::name.name, "p{2,}"))

results.forEach { result ->
println(result)
}
// end-find-evaluation
}
1 change: 1 addition & 0 deletions source/read.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ Read Data from MongoDB
:titlesonly:
:maxdepth: 1

/read/specify-a-query
/read/retrieve
/read/project
/read/specify-documents-to-return
Expand Down
266 changes: 266 additions & 0 deletions source/read/specify-a-query.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,266 @@
.. _kotlin-sync-specify-query:

===============
Specify a Query
===============

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: expressions, operations, read, write, filter

Overview
--------

In this guide, you can learn how to specify a query by using the {+driver-short+}.

You can refine the set of documents that a query returns by creating a
**query filter**. A query filter is an expression that specifies the search
criteria MongoDB uses to match documents in a read or write operation.
In a query filter, you can prompt the driver to search for documents with an
exact match to your query, or you can compose query filters to express more
complex matching criteria.

Sample Data
~~~~~~~~~~~

The examples in this guide run operations on a collection called
``fruits`` that contains the following documents:

.. code-block:: json

{ "_id": 1, "name": "apples", "quantity": 5, "rating": 3, "color": "red", "type": ["fuji", "honeycrisp"] },
{ "_id": 2, "name": "bananas", "quantity": 7, "rating": 4, "color": "yellow", "type": ["cavendish"] },
{ "_id": 3, "name": "oranges", "quantity": 6, "rating": 2, "type": ["naval", "mandarin"] },
{ "_id": 4, "name": "pineapple", "quantity": 3, "rating": 5, "color": "yellow" },

The documents in this collection are modeled by the following {+language+} data class:

.. literalinclude:: /includes/read/specify-a-query.kt
:start-after: start-data-class
:end-before: end-data-class
:language: kotlin
:copyable:

The following code example shows how to create a database and collection, then
insert the sample documents into your collection:

.. literalinclude:: /includes/read/specify-a-query.kt
:start-after: start-sample-data
:end-before: end-sample-data
:language: kotlin
:dedent:
:copyable:

Exact Match
-----------

Literal value queries return documents with an exact match to your query filter.

The following example specifies a query filter as a parameter to the ``find()``
method. The code returns all documents with a ``color`` field value of ``"yellow"``.

.. io-code-block::
:copyable: true

.. input:: /includes/read/specify-a-query.kt
:start-after: start-find-exact
:end-before: end-find-exact
:language: kotlin
:dedent:

.. output::
:visible: false

Fruit(id=2, name=bananas, quantity=7, rating=4, color=yellow, type=[cavendish])
Fruit(id=4, name=pineapples, quantity=3, rating=5, color=yellow, type=null)

Comparison Operators
--------------------

Comparison operators evaluate a document field value against a specified value
in your query filter. The following is a list of common comparison operators:

- ``$gt``: Greater than
- ``$lte``: Less than or Equal
- ``$ne``: Not equal

To view a full list of comparison operators, see the :manual:`Comparison Query Operators
</reference/operator/query-comparison/>` guide in the MongoDB Server manual.

The following example specifies a comparison operator in a query filter as a
parameter to the ``find()`` method. The code returns all documents with a
``rating`` field value greater than ``2``.

.. io-code-block::
:copyable: true

.. input:: /includes/read/specify-a-query.kt
:start-after: start-find-comparison
:end-before: end-find-comparison
:language: kotlin
:dedent:

.. output::
:visible: false

Fruit(id=1, name=apples, quantity=5, rating=3, color=red, type=[fuji, honeycrisp])
Fruit(id=2, name=bananas, quantity=7, rating=4, color=yellow, type=[cavendish])
Fruit(id=4, name=pineapples, quantity=3, rating=5, color=yellow, type=null)

Logical Operators
-----------------

Logical operators match documents by using logic applied to the results of two or
more sets of expressions. The following is a list of logical operators:

- ``$and``, which returns all documents that match the conditions of *all* clauses
- ``$or``, which returns all documents that match the conditions of *one* clause
- ``$nor``, which returns all documents that *do not* match the conditions of any clause
- ``$not``, which returns all documents that *do not* match the expression

To learn more about logical operators, see the :manual:`Logical Query Operators
</reference/operator/query-logical/>` guide in the MongoDB Server manual.

The following example specifies a logical operator in a query filter as a
parameter to the ``find()`` method. The code returns all documents with a
``quantity`` field value greater than ``5`` **or** a ``color`` field value of
``"yellow"``.

.. io-code-block::
:copyable: true

.. input:: /includes/read/specify-a-query.kt
:start-after: start-find-logical
:end-before: end-find-logical
:language: kotlin
:dedent:

.. output::
:visible: false

Fruit(id=2, name=bananas, quantity=7, rating=4, color=yellow, type=[cavendish])
Fruit(id=3, name=oranges, quantity=6, rating=2, color=null, type=[naval, mandarin])
Fruit(id=4, name=pineapples, quantity=3, rating=5, color=yellow, type=null)

Array Operators
---------------

Array operators match documents based on the value or quantity of elements in an
array field. The following is a list of available array operators:

- ``$all``, which returns documents with arrays that contain all elements in the query
- ``$elemMatch``, which returns documents if an element in their array field matches all conditions in the query
- ``$size``, which returns all documents with arrays of a specified size

To learn more about array operators, see the :manual:`Array Query Operators
</reference/operator/query-array/>` guide in the MongoDB Server manual.

The following example specifies an array operator in a query filter as a
parameter to the ``find()`` method. The code returns all documents with a
``type`` array field containing exactly ``2`` elements.

.. io-code-block::
:copyable: true

.. input:: /includes/read/specify-a-query.kt
:start-after: start-find-array
:end-before: end-find-array
:language: kotlin
:dedent:

.. output::
:visible: false

Fruit(id=1, name=apples, quantity=5, rating=3, color=red, type=[fuji, honeycrisp])
Fruit(id=3, name=oranges, quantity=6, rating=2, color=null, type=[naval, mandarin])

Element Operators
-----------------

Element operators query data based on the presence or type of a field.

To learn more about element operators, see the :manual:`Element Query Operators
</reference/operator/query-element/>` guide in the MongoDB Server manual.

The following example specifies an element operator in a query filter as a
parameter to the ``find()`` method. The code returns all documents that have a
``color`` field.

.. io-code-block::
:copyable: true

.. input:: /includes/read/specify-a-query.kt
:start-after: start-find-element
:end-before: end-find-element
:language: kotlin
:dedent:

.. output::
:visible: false

Fruit(id=1, name=apples, quantity=5, rating=3, color=red, type=[fuji, honeycrisp])
Fruit(id=2, name=bananas, quantity=7, rating=4, color=yellow, type=[cavendish])
Fruit(id=4, name=pineapples, quantity=3, rating=5, color=yellow, type=null)

Evaluation Operators
--------------------

Evaluation operators return data based on evaluations of either individual
fields or the entire collection's documents.

The following is a list of common evaluation operators:

- ``$text``, which performs a text search on the documents
- ``$regex``, which returns documents that match a specified regular expression
- ``$mod``, which performs a :wikipedia:`modulo <w/index.php?title=Modulo&oldid=1226348145>`
operation on the value of a field and returns documents where the remainder is a specified
value

To view a full list of evaluation operators, see the :manual:`Evaluation Query Operators
</reference/operator/query-evaluation/>` guide in the MongoDB Server manual.

The following example specifies an evaluation operator in a query filter as a
parameter to the ``find()`` method. The code uses a regular expression to return
all documents with a ``name`` field value that has at least two consecutive
``"p"`` characters.

.. io-code-block::
:copyable: true

.. input:: /includes/read/specify-a-query.kt
:start-after: start-find-evaluation
:end-before: end-find-evaluation
:language: kotlin
:dedent:

.. output::
:visible: false

Fruit(id=1, name=apples, quantity=5, rating=3, color=red, type=[fuji, honeycrisp])
Fruit(id=4, name=pineapples, quantity=3, rating=5, color=yellow, type=null)

Additional Information
----------------------

To learn more about querying documents, see the :manual:`Query Documents
</tutorial/query-documents/>` guide in the MongoDB Server manual.

To learn more about retrieving documents with the {+driver-short+}, see
:ref:`kotlin-sync-retrieve`.
Comment on lines +257 to +258
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note for reviewers: The retrieve page here is currently also in review. This PR should be merged in after the retrieve page is merged.

Link to Retrieve page PR


API Documentation
~~~~~~~~~~~~~~~~~

To learn more about any of the methods or types discussed in this
guide, see the following API documentation:

- `find() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/find.html>`__