$max

在本页面

Definition

$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")
}
首页