@@ -133,14 +133,14 @@ greater than ``200``:
133133
134134.. code-block:: javascript
135135
136- db.inventory.aggregate([
136+ db.inventory.aggregate( [
137137 {
138138 $match:
139139 { $expr:
140140 { $gt: [ { $getField: "price.usd" }, 200 ] }
141141 }
142142 }
143- ])
143+ ] )
144144
145145The operation returns the following results:
146146
@@ -171,14 +171,14 @@ products have a ``$price`` greater than ``200``:
171171
172172.. code-block:: javascript
173173
174- db.inventory.aggregate([
174+ db.inventory.aggregate( [
175175 {
176176 $match:
177177 { $expr:
178178 { $gt: [ { $getField: {$literal: "$price" } }, 200 ] }
179179 }
180180 }
181- ])
181+ ] )
182182
183183The operation returns the following results:
184184
@@ -190,3 +190,75 @@ The operation returns the following results:
190190 { _id: 4, item: 'leather boots', qty: 300, '$price': 249.99 }
191191 ]
192192
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