Skip to content

Commit ffd5d1f

Browse files
authored
DOCSP-41133: Specify a Query (#11)
1 parent 83432bc commit ffd5d1f

File tree

3 files changed

+360
-0
lines changed

3 files changed

+360
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
package org.example
2+
import com.mongodb.ConnectionString
3+
import com.mongodb.MongoClientSettings
4+
import com.mongodb.client.model.Filters.*
5+
import com.mongodb.kotlin.client.MongoClient
6+
import org.bson.codecs.pojo.annotations.BsonId
7+
8+
// start-data-class
9+
data class Fruit(
10+
@BsonId
11+
val id: Int,
12+
val name: String,
13+
val quantity: Int,
14+
val rating: Int,
15+
val color: String,
16+
val type: List<String>
17+
)
18+
// end-data-class
19+
20+
fun main() {
21+
// start-sample-data
22+
val uri = "<connection string URI>"
23+
24+
val settings = MongoClientSettings.builder()
25+
.applyConnectionString(ConnectionString(uri))
26+
.retryWrites(true)
27+
.build()
28+
29+
val mongoClient = MongoClient.create(settings)
30+
val database = mongoClient.getDatabase("sample_fruit")
31+
val collection = database.getCollection<Fruit>("fruits")
32+
33+
collection.insertMany(listOf(
34+
Fruit(1, "apples", 5, 3, "red", listOf("fuji", "honeycrisp")),
35+
Fruit(2, "bananas", 7, 4, "yellow", listOf("cavendish")),
36+
Fruit(3, "oranges", 6, 2, null, listOf("naval", "mandarin")),
37+
Fruit(4, "pineapples", 3, 5, "yellow", null)
38+
))
39+
// end-sample-data
40+
41+
// start-find-exact
42+
val results = collection.find(eq(Fruit::color.name, "yellow"))
43+
44+
results.forEach { result ->
45+
println(result);
46+
}
47+
// end-find-exact
48+
49+
// start-find-comparison
50+
val results = collection.find(gt(Fruit::rating.name, 2))
51+
52+
results.forEach { result ->
53+
println(result)
54+
}
55+
// end-find-comparison
56+
57+
// start-find-logical
58+
val results = collection.find(
59+
or(
60+
gt(Fruit::quantity.name, 5),
61+
eq(Fruit::color.name, "yellow")
62+
)
63+
)
64+
65+
results.forEach { result ->
66+
println(result)
67+
}
68+
// end-find-logical
69+
70+
// start-find-array
71+
val results = collection.find(size(Fruit::type.name, 2))
72+
73+
results.forEach { result ->
74+
println(result)
75+
}
76+
// end-find-array
77+
78+
// start-find-element
79+
val results = collection.find(exists(Fruit::color.name))
80+
81+
results.forEach { result ->
82+
println(result)
83+
}
84+
// end-find-element
85+
86+
// start-find-evaluation
87+
val results = collection.find(regex(Fruit::name.name, "p{2,}"))
88+
89+
results.forEach { result ->
90+
println(result)
91+
}
92+
// end-find-evaluation
93+
}

source/read.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ Read Data from MongoDB
2222
:titlesonly:
2323
:maxdepth: 1
2424

25+
/read/specify-a-query
2526
/read/retrieve
2627
/read/project
2728
/read/specify-documents-to-return

source/read/specify-a-query.txt

Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
1+
.. _kotlin-sync-specify-query:
2+
3+
===============
4+
Specify a Query
5+
===============
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: expressions, operations, read, write, filter
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to specify a query by using the {+driver-short+}.
24+
25+
You can refine the set of documents that a query returns by creating a
26+
**query filter**. A query filter is an expression that specifies the search
27+
criteria MongoDB uses to match documents in a read or write operation.
28+
In a query filter, you can prompt the driver to search for documents with an
29+
exact match to your query, or you can compose query filters to express more
30+
complex matching criteria.
31+
32+
Sample Data
33+
~~~~~~~~~~~
34+
35+
The examples in this guide run operations on a collection called
36+
``fruits`` that contains the following documents:
37+
38+
.. code-block:: json
39+
40+
{ "_id": 1, "name": "apples", "quantity": 5, "rating": 3, "color": "red", "type": ["fuji", "honeycrisp"] },
41+
{ "_id": 2, "name": "bananas", "quantity": 7, "rating": 4, "color": "yellow", "type": ["cavendish"] },
42+
{ "_id": 3, "name": "oranges", "quantity": 6, "rating": 2, "type": ["naval", "mandarin"] },
43+
{ "_id": 4, "name": "pineapple", "quantity": 3, "rating": 5, "color": "yellow" },
44+
45+
The documents in this collection are modeled by the following {+language+} data class:
46+
47+
.. literalinclude:: /includes/read/specify-a-query.kt
48+
:start-after: start-data-class
49+
:end-before: end-data-class
50+
:language: kotlin
51+
:copyable:
52+
53+
The following code example shows how to create a database and collection, then
54+
insert the sample documents into your collection:
55+
56+
.. literalinclude:: /includes/read/specify-a-query.kt
57+
:start-after: start-sample-data
58+
:end-before: end-sample-data
59+
:language: kotlin
60+
:dedent:
61+
:copyable:
62+
63+
Exact Match
64+
-----------
65+
66+
Literal value queries return documents with an exact match to your query filter.
67+
68+
The following example specifies a query filter as a parameter to the ``find()``
69+
method. The code returns all documents with a ``color`` field value of ``"yellow"``.
70+
71+
.. io-code-block::
72+
:copyable: true
73+
74+
.. input:: /includes/read/specify-a-query.kt
75+
:start-after: start-find-exact
76+
:end-before: end-find-exact
77+
:language: kotlin
78+
:dedent:
79+
80+
.. output::
81+
:visible: false
82+
83+
Fruit(id=2, name=bananas, quantity=7, rating=4, color=yellow, type=[cavendish])
84+
Fruit(id=4, name=pineapples, quantity=3, rating=5, color=yellow, type=null)
85+
86+
Comparison Operators
87+
--------------------
88+
89+
Comparison operators evaluate a document field value against a specified value
90+
in your query filter. The following is a list of common comparison operators:
91+
92+
- ``$gt``: Greater than
93+
- ``$lte``: Less than or Equal
94+
- ``$ne``: Not equal
95+
96+
To view a full list of comparison operators, see the :manual:`Comparison Query Operators
97+
</reference/operator/query-comparison/>` guide in the MongoDB Server manual.
98+
99+
The following example specifies a comparison operator in a query filter as a
100+
parameter to the ``find()`` method. The code returns all documents with a
101+
``rating`` field value greater than ``2``.
102+
103+
.. io-code-block::
104+
:copyable: true
105+
106+
.. input:: /includes/read/specify-a-query.kt
107+
:start-after: start-find-comparison
108+
:end-before: end-find-comparison
109+
:language: kotlin
110+
:dedent:
111+
112+
.. output::
113+
:visible: false
114+
115+
Fruit(id=1, name=apples, quantity=5, rating=3, color=red, type=[fuji, honeycrisp])
116+
Fruit(id=2, name=bananas, quantity=7, rating=4, color=yellow, type=[cavendish])
117+
Fruit(id=4, name=pineapples, quantity=3, rating=5, color=yellow, type=null)
118+
119+
Logical Operators
120+
-----------------
121+
122+
Logical operators match documents by using logic applied to the results of two or
123+
more sets of expressions. The following is a list of logical operators:
124+
125+
- ``$and``, which returns all documents that match the conditions of *all* clauses
126+
- ``$or``, which returns all documents that match the conditions of *one* clause
127+
- ``$nor``, which returns all documents that *do not* match the conditions of any clause
128+
- ``$not``, which returns all documents that *do not* match the expression
129+
130+
To learn more about logical operators, see the :manual:`Logical Query Operators
131+
</reference/operator/query-logical/>` guide in the MongoDB Server manual.
132+
133+
The following example specifies a logical operator in a query filter as a
134+
parameter to the ``find()`` method. The code returns all documents with a
135+
``quantity`` field value greater than ``5`` **or** a ``color`` field value of
136+
``"yellow"``.
137+
138+
.. io-code-block::
139+
:copyable: true
140+
141+
.. input:: /includes/read/specify-a-query.kt
142+
:start-after: start-find-logical
143+
:end-before: end-find-logical
144+
:language: kotlin
145+
:dedent:
146+
147+
.. output::
148+
:visible: false
149+
150+
Fruit(id=2, name=bananas, quantity=7, rating=4, color=yellow, type=[cavendish])
151+
Fruit(id=3, name=oranges, quantity=6, rating=2, color=null, type=[naval, mandarin])
152+
Fruit(id=4, name=pineapples, quantity=3, rating=5, color=yellow, type=null)
153+
154+
Array Operators
155+
---------------
156+
157+
Array operators match documents based on the value or quantity of elements in an
158+
array field. The following is a list of available array operators:
159+
160+
- ``$all``, which returns documents with arrays that contain all elements in the query
161+
- ``$elemMatch``, which returns documents if an element in their array field matches all conditions in the query
162+
- ``$size``, which returns all documents with arrays of a specified size
163+
164+
To learn more about array operators, see the :manual:`Array Query Operators
165+
</reference/operator/query-array/>` guide in the MongoDB Server manual.
166+
167+
The following example specifies an array operator in a query filter as a
168+
parameter to the ``find()`` method. The code returns all documents with a
169+
``type`` array field containing exactly ``2`` elements.
170+
171+
.. io-code-block::
172+
:copyable: true
173+
174+
.. input:: /includes/read/specify-a-query.kt
175+
:start-after: start-find-array
176+
:end-before: end-find-array
177+
:language: kotlin
178+
:dedent:
179+
180+
.. output::
181+
:visible: false
182+
183+
Fruit(id=1, name=apples, quantity=5, rating=3, color=red, type=[fuji, honeycrisp])
184+
Fruit(id=3, name=oranges, quantity=6, rating=2, color=null, type=[naval, mandarin])
185+
186+
Element Operators
187+
-----------------
188+
189+
Element operators query data based on the presence or type of a field.
190+
191+
To learn more about element operators, see the :manual:`Element Query Operators
192+
</reference/operator/query-element/>` guide in the MongoDB Server manual.
193+
194+
The following example specifies an element operator in a query filter as a
195+
parameter to the ``find()`` method. The code returns all documents that have a
196+
``color`` field.
197+
198+
.. io-code-block::
199+
:copyable: true
200+
201+
.. input:: /includes/read/specify-a-query.kt
202+
:start-after: start-find-element
203+
:end-before: end-find-element
204+
:language: kotlin
205+
:dedent:
206+
207+
.. output::
208+
:visible: false
209+
210+
Fruit(id=1, name=apples, quantity=5, rating=3, color=red, type=[fuji, honeycrisp])
211+
Fruit(id=2, name=bananas, quantity=7, rating=4, color=yellow, type=[cavendish])
212+
Fruit(id=4, name=pineapples, quantity=3, rating=5, color=yellow, type=null)
213+
214+
Evaluation Operators
215+
--------------------
216+
217+
Evaluation operators return data based on evaluations of either individual
218+
fields or the entire collection's documents.
219+
220+
The following is a list of common evaluation operators:
221+
222+
- ``$text``, which performs a text search on the documents
223+
- ``$regex``, which returns documents that match a specified regular expression
224+
- ``$mod``, which performs a :wikipedia:`modulo <w/index.php?title=Modulo&oldid=1226348145>`
225+
operation on the value of a field and returns documents where the remainder is a specified
226+
value
227+
228+
To view a full list of evaluation operators, see the :manual:`Evaluation Query Operators
229+
</reference/operator/query-evaluation/>` guide in the MongoDB Server manual.
230+
231+
The following example specifies an evaluation operator in a query filter as a
232+
parameter to the ``find()`` method. The code uses a regular expression to return
233+
all documents with a ``name`` field value that has at least two consecutive
234+
``"p"`` characters.
235+
236+
.. io-code-block::
237+
:copyable: true
238+
239+
.. input:: /includes/read/specify-a-query.kt
240+
:start-after: start-find-evaluation
241+
:end-before: end-find-evaluation
242+
:language: kotlin
243+
:dedent:
244+
245+
.. output::
246+
:visible: false
247+
248+
Fruit(id=1, name=apples, quantity=5, rating=3, color=red, type=[fuji, honeycrisp])
249+
Fruit(id=4, name=pineapples, quantity=3, rating=5, color=yellow, type=null)
250+
251+
Additional Information
252+
----------------------
253+
254+
To learn more about querying documents, see the :manual:`Query Documents
255+
</tutorial/query-documents/>` guide in the MongoDB Server manual.
256+
257+
To learn more about retrieving documents with the {+driver-short+}, see
258+
:ref:`kotlin-sync-retrieve`.
259+
260+
API Documentation
261+
~~~~~~~~~~~~~~~~~
262+
263+
To learn more about any of the methods or types discussed in this
264+
guide, see the following API documentation:
265+
266+
- `find() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/find.html>`__

0 commit comments

Comments
 (0)