定义
语法
$getField 通过以下语法实现:
{ $getField: { field: <String>, input: <Object> } }
字段 | 类型 | 说明 |
|---|---|---|
| 字符串 | |
| 对象 |
$getField 具有以下用于从 $$CURRENT 检索字段值的速记语法:
{ $getField: <String> }
对于此语法,参数等效于上述 field 的值。
行为
如果您指定的
field不存在于input对象中,或者如果您未指定input对象,则不存在于$$CURRENT中,$getField将返回missing。如果
input的计算结果为missing、undefined或null,$getField将返回null。如果
input的计算结果为对象、missing、undefined或null以外的任何值,$getField将返回错误。$getField不会隐式遍历对象或数组。例如,$getField将a.b.c的field值计算为顶级字段a.b.c,而不是嵌套字段{ a: { b: { c: } } }。
示例
包含句点 () 的查询字段.
考虑包含以下文档的 inventory 集合:
db.inventory.insertMany( [ { _id: 1, item: "sweatshirt", "price.usd": 45.99, qty: 300 }, { _id: 2, item: "winter coat", "price.usd": 499.99, qty: 200 }, { _id: 3, item: "sun dress", "price.usd": 199.99, qty: 250 }, { _id: 4, item: "leather boots", "price.usd": 249.99, qty: 300 }, { _id: 5, item: "bow tie", "price.usd": 9.99, qty: 180 } ] )
以下操作使用 $getField 和 $gt 操作符来查找哪些产品的 price.usd 大于 200:
db.inventory.aggregate( [ { $match: { $expr: { $gt: [ { $getField: "price.usd" }, 200 ] } } } ] )
操作返回以下结果:
[ { _id: 2, item: 'winter coat', qty: 200, 'price.usd': 499.99 }, { _id: 4, item: 'leather boots', qty: 300, 'price.usd': 249.99 } ]
以美元符号 ($ ) 开头的查询字段
考虑包含以下文档的 inventory 集合:
db.inventory.insertMany( [ { _id: 1, item: "sweatshirt", "$price": 45.99, qty: 300 }, { _id: 2, item: "winter coat", "$price": 499.99, qty: 200 }, { _id: 3, item: "sun dress", "$price": 199.99, qty: 250 }, { _id: 4, item: "leather boots", "$price": 249.99, qty: 300 }, { _id: 5, item: "bow tie", "$price": 9.99, qty: 180 } ] )
以下操作使用 $getField、$gt 和 $literal 操作符来查找哪些产品的 $price 大于 200:
db.inventory.aggregate( [ { $match: { $expr: { $gt: [ { $getField: {$literal: "$price" } }, 200 ] } } } ] )
操作返回以下结果:
[ { _id: 2, item: 'winter coat', qty: 200, '$price': 499.99 }, { _id: 4, item: 'leather boots', qty: 300, '$price': 249.99 } ]
查询子文档中的字段
使用以下文档创建 inventory 集合:
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 } } ] )
以下操作将返回 $small 项的数量小于或等于 20 的文档。
db.inventory.aggregate( [ { $match: { $expr: { $lte: [ { $getField: { field: { $literal: "$small" }, input: "$quantity" } }, 20 ] } } } ] )
使用这些操作符来查询集合:
示例输出:
[ { _id: 3, item: 'sun dress', 'price.usd': 199.99, quantity: { '$large': 45, '$medium': 40, '$small': 5 } } ]