On this page
$max
在本页面
Definition
$max
- $max运算符将字段的值更新为指定的值如果指定的值 大于 字段的当前值。 $max运算符可以使用BSON 比较 Sequences比较不同类型的值。
$max运算符表达式的形式为:
{ $max: { <field1>: <value1>, ... } }
要在嵌入式文档或数组中指定<field>
,请使用dot notation。
Behavior
如果该字段不存在,则$max运算符将该字段设置为指定的值。
Examples
使用$ max 比较数字
考虑集合scores
中的以下文档:
{ _id: 1, highScore: 800, lowScore: 200 }
该文档的highScore
当前具有值800
。以下操作使用$max比较800
和指定的值950
并将highScore
的值更新为950
,因为950
大于800
:
db.scores.update( { _id: 1 }, { $max: { highScore: 950 } } )
scores
集合现在包含以下修改后的文档:
{ _id: 1, highScore: 950, lowScore: 200 }
由于字段highScore
的当前值,即950
大于870
,因此下一个操作无效:
db.scores.update( { _id: 1 }, { $max: { highScore: 870 } } )
该文档在scores
集合中保持不变:
{ _id: 1, highScore: 950, lowScore: 200 }
使用$ max 比较日期
考虑集合tags
中的以下文档:
{
_id: 1,
desc: "crafts",
dateEntered: ISODate("2013-10-01T05:00:00Z"),
dateExpired: ISODate("2013-10-01T16:38:16.163Z")
}
以下操作将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") } }
)
该操作不更新dateExpired
字段:
{
_id: 1,
desc: "decorative arts",
dateEntered: ISODate("2013-10-01T05:00:00Z"),
dateExpired: ISODate("2013-10-01T16:38:16.163Z")
}