$max

On this page本页内容

Definition定义

$max

The $max operator updates the value of the field to a specified value if the specified value is greater than the current value of the field. 如果指定值大于字段的当前值,$max运算符将字段的值更新为指定值。The $max operator can compare values of different types, using the BSON comparison order.$max运算符可以使用BSON比较顺序比较不同类型的值。

The $max operator expression has the form:$max运算符表达式的形式如下:

{ $max: { <field1>: <value1>, ... } }

To specify a <field> in an embedded document or in an array, use dot notation.若要在嵌入式文档或数组中指定一个<field>,请使用点表示法

Behavior行为

If the field does not exists, the $max operator sets the field to the specified value.如果该字段不存在,$max运算符将该字段设置为指定值。

Examples示例

Use $max to Compare Numbers使用$max来比较数字

Consider the following document in the collection scores:在集合scores中考虑以下文档:

{ _id: 1, highScore: 800, lowScore: 200 }

The highScore for the document currently has the value 800. 文档的highScore当前为800The following operation uses $max to compare the 800 and the specified value 950 and updates the value of highScore to 950 since 950 is greater than 800:以下操作使用$max比较800和指定值950,并将highScore的值更新为950,因为950大于800

db.scores.update( { _id: 1 }, { $max: { highScore: 950 } } )

The scores collection now contains the following modified document:scores集合现在包含以下修改过的文档:

{ _id: 1, highScore: 950, lowScore: 200 }

The next operation has no effect since the current value of the field highScore, i.e. 950, is greater than 870:由于字段highScore(即950)的当前值大于870,因此下一个操作无效:

db.scores.update( { _id: 1 }, { $max: { highScore: 870 } } )

The document remains unchanged in the scores collection:该文档在scores集合中保持不变:

{ _id: 1, highScore: 950, lowScore: 200 }

Use $max to Compare Dates使用$max来比较日期

Consider the following document in the collection tags:在集合tags中考虑以下文档:

{
  _id: 1,
  desc: "crafts",
  dateEntered: ISODate("2013-10-01T05:00:00Z"),
  dateExpired: ISODate("2013-10-01T16:38:16.163Z")
}

The following operation compares the current value of the dateExpired field, i.e. ISODate("2013-10-01T16:38:16.163Z"), with the specified date new Date("2013-09-30") to determine whether to update the field:以下操作将dateExpired字段的当前值(即ISODate("2013-10-01T16:38:16.163Z"))与指定的日期new Date("2013-09-30")进行比较,以确定是否更新该字段:

db.tags.update(
   { _id: 1 },
   { $max: { dateExpired: new Date("2013-09-30") } }
)

The operation does not update the dateExpired field:该操作不会更新dateExpired字段:

{
   _id: 1,
   desc: "decorative arts",
   dateEntered: ISODate("2013-10-01T05:00:00Z"),
dateExpired: ISODate("2013-10-01T16:38:16.163Z")}