Database Manual / Reference / Query Language / Query Predicates / Comparison

$gt (expression operator)(表达式运算符)

Definition定义

$gt

$gt selects those documents where the value of the specified field is greater than (i.e. >) the specified value.选择那些指定字段的值大于(即>)指定值的文档。

For most data types, comparison operators only perform comparisons on fields where the BSON type matches the query value's type. 对于大多数数据类型,比较运算符仅对BSON类型与查询值类型匹配的字段执行比较。MongoDB supports limited cross-BSON comparison through Type Bracketing.MongoDB支持通过类型花括号进行有限的跨BSON比较。

Compatibility兼容性

You can use $gt for deployments hosted in the following environments:您可以将$gt用于在以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

The $gt operator has the following form:$gt运算符具有以下形式:

{ field: { $gt: value } }

Examples示例

The following examples use the inventory collection. Create the collection:以下示例使用inventory集合。创建集合:

db.inventory.insertMany( [
{
item: "nuts", quantity: 30,
carrier: { name: "Shipit", fee: 3 }
},
{
item: "bolts", quantity: 50,
carrier: { name: "Shipit", fee: 4 }
},
{
item: "washers", quantity: 10,
carrier: { name: "Shipit", fee: 1 }
}
] )

Match Document Fields匹配文档字段

Select all documents in the inventory collection where quantity is greater than 20:选择inventory领用中quantity大于20的所有单据:

db.inventory.find( { quantity: { $gt: 20 } } )

Example output:输出示例:

{
_id: ObjectId("61ba25cbfe687fce2f042414"),
item: 'nuts',
quantity: 30,
carrier: { name: 'Shipit', fee: 3 }
},
{
_id: ObjectId("61ba25cbfe687fce2f042415"),
item: 'bolts',
quantity: 50,
carrier: { name: 'Shipit', fee: 4 }
}

Perform an Update Based on Embedded Document Fields基于嵌入式文档字段执行更新

The following example sets the price field based on a $gt comparison against a field in an embedded document.以下示例根据$gt与嵌入式文档中的字段进行比较来设置price字段。

db.inventory.updateOne(
{ "carrier.fee": { $gt: 2 } }, { $set: { "price": 9.99 } }
)

Example output:输出示例:

{
_id: ObjectId("61ba3ec9fe687fce2f042417"),
item: 'nuts',
quantity: 30,
carrier: { name: 'Shipit', fee: 3 },
price: 9.99
},
{
_id: ObjectId("61ba3ec9fe687fce2f042418"),
item: 'bolts',
quantity: 50,
carrier: { name: 'Shipit', fee: 4 }
},
{
_id: ObjectId("61ba3ec9fe687fce2f042419"),
item: 'washers',
quantity: 10,
carrier: { name: 'Shipit', fee: 1 }
}

This updateOne() operation searches for an embedded document, carrier, with a subfield named fee. updateOne()操作搜索一个嵌入式文档carrier,其中包含一个名为fee的子字段。It sets { price: 9.99 } in the first document it finds where fee has a value greater than 2.它在找到的第一个fee值大于2的文档中设置{ price: 9.99 }

To set the value of the price field in all documents where carrier.fee is greater than 2, use updateMany().要在carrier.fee大于2的所有文档中设置price字段的值,请使用updateMany()