diff --git a/source/reference/operator/aggregation/getField.txt b/source/reference/operator/aggregation/getField.txt index 1268f5b7871..b389bc8b51c 100644 --- a/source/reference/operator/aggregation/getField.txt +++ b/source/reference/operator/aggregation/getField.txt @@ -133,14 +133,14 @@ greater than ``200``: .. code-block:: javascript - db.inventory.aggregate([ + db.inventory.aggregate( [ { $match: { $expr: { $gt: [ { $getField: "price.usd" }, 200 ] } } } - ]) + ] ) The operation returns the following results: @@ -171,14 +171,14 @@ products have a ``$price`` greater than ``200``: .. code-block:: javascript - db.inventory.aggregate([ + db.inventory.aggregate( [ { $match: { $expr: { $gt: [ { $getField: {$literal: "$price" } }, 200 ] } } } - ]) + ] ) The operation returns the following results: @@ -190,3 +190,75 @@ The operation returns the following results: { _id: 4, item: 'leather boots', qty: 300, '$price': 249.99 } ] +Query a Field in a Sub-document +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Create an ``inventory`` collection with the following documents: + +.. code-block:: javascript + + db.inventory.insertMany( [ + { "_id" : 1, "item" : "sweatshirt", "price.usd": 45.99, + "quantity": { "$large": 50, "$medium": 50, "$small": 25 } + }, + { "_id" : 2, "item" : "winter coat", "price.usd": 499.99, + "quantity": { "$large": 35, "$medium": 35, "$small": 35 } + }, + { "_id" : 3, "item" : "sun dress", "price.usd": 199.99, + "quantity": { "$large": 45, "$medium": 40, "$small": 5 } + }, + { "_id" : 4, "item" : "leather boots", "price.usd": 249.99, + "quantity": { "$large": 20, "$medium": 30, "$small": 40 } + }, + { "_id" : 5, "item" : "bow tie", "price.usd": 9.99, + "quantity": { "$large": 0, "$medium": 10, "$small": 75 } + } + ] ) + +The following operation returns documents where the number of +``$small`` items is less than or equal to ``20``. + +.. code-block:: javascript + :emphasize-lines: 6-8 + + db.inventory.aggregate( [ + { $match: + { $expr: + { $lte: + [ + { $getField: + { field: { $literal: "$small" }, + input: "$quantity" + } + }, + 20 + ] + } + } + } + ] ) + +Use these operators to query the collection: + +- The :expression:`$lte` operator finds values less than or equal to + 20. +- :expression:`$getField` requires explicit ``field`` and ``input`` + parameters because the ``$small`` field is part of a + sub-document. +- :expression:`$getField` uses :expression:`$literal` to evaluate + "``$small``", because the field name has a dollar sign (``$``) in it. + +Example output: + +.. code-block:: javascript + :copyable: false + + [ + { + _id: 3, + item: 'sun dress', + 'price.usd': 199.99, + quantity: { '$large': 45, '$medium': 40, '$small': 5 } + } + ] +