@@ -133,14 +133,14 @@ greater than ``200``:
133
133
134
134
.. code-block:: javascript
135
135
136
- db.inventory.aggregate([
136
+ db.inventory.aggregate( [
137
137
{
138
138
$match:
139
139
{ $expr:
140
140
{ $gt: [ { $getField: "price.usd" }, 200 ] }
141
141
}
142
142
}
143
- ])
143
+ ] )
144
144
145
145
The operation returns the following results:
146
146
@@ -171,14 +171,14 @@ products have a ``$price`` greater than ``200``:
171
171
172
172
.. code-block:: javascript
173
173
174
- db.inventory.aggregate([
174
+ db.inventory.aggregate( [
175
175
{
176
176
$match:
177
177
{ $expr:
178
178
{ $gt: [ { $getField: {$literal: "$price" } }, 200 ] }
179
179
}
180
180
}
181
- ])
181
+ ] )
182
182
183
183
The operation returns the following results:
184
184
@@ -190,3 +190,75 @@ The operation returns the following results:
190
190
{ _id: 4, item: 'leather boots', qty: 300, '$price': 249.99 }
191
191
]
192
192
193
+ Query a Field in a Sub-document
194
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
195
+
196
+ Create an ``inventory`` collection with the following documents:
197
+
198
+ .. code-block:: javascript
199
+
200
+ db.inventory.insertMany( [
201
+ { "_id" : 1, "item" : "sweatshirt", "price.usd": 45.99,
202
+ "quantity": { "$large": 50, "$medium": 50, "$small": 25 }
203
+ },
204
+ { "_id" : 2, "item" : "winter coat", "price.usd": 499.99,
205
+ "quantity": { "$large": 35, "$medium": 35, "$small": 35 }
206
+ },
207
+ { "_id" : 3, "item" : "sun dress", "price.usd": 199.99,
208
+ "quantity": { "$large": 45, "$medium": 40, "$small": 5 }
209
+ },
210
+ { "_id" : 4, "item" : "leather boots", "price.usd": 249.99,
211
+ "quantity": { "$large": 20, "$medium": 30, "$small": 40 }
212
+ },
213
+ { "_id" : 5, "item" : "bow tie", "price.usd": 9.99,
214
+ "quantity": { "$large": 0, "$medium": 10, "$small": 75 }
215
+ }
216
+ ] )
217
+
218
+ The following operation returns documents where the number of
219
+ ``$small`` items is less than or equal to ``20``.
220
+
221
+ .. code-block:: javascript
222
+ :emphasize-lines: 6-8
223
+
224
+ db.inventory.aggregate( [
225
+ { $match:
226
+ { $expr:
227
+ { $lte:
228
+ [
229
+ { $getField:
230
+ { field: { $literal: "$small" },
231
+ input: "$quantity"
232
+ }
233
+ },
234
+ 20
235
+ ]
236
+ }
237
+ }
238
+ }
239
+ ] )
240
+
241
+ Use these operators to query the collection:
242
+
243
+ - The :expression:`$lte` operator finds values less than or equal to
244
+ 20.
245
+ - :expression:`$getField` requires explicit ``field`` and ``input``
246
+ parameters because the ``$small`` field is part of a
247
+ sub-document.
248
+ - :expression:`$getField` uses :expression:`$literal` to evaluate
249
+ "``$small``", because the field name has a dollar sign (``$``) in it.
250
+
251
+ Example output:
252
+
253
+ .. code-block:: javascript
254
+ :copyable: false
255
+
256
+ [
257
+ {
258
+ _id: 3,
259
+ item: 'sun dress',
260
+ 'price.usd': 199.99,
261
+ quantity: { '$large': 45, '$medium': 40, '$small': 5 }
262
+ }
263
+ ]
264
+
0 commit comments