$max

Definition

  • $max
  • The $max operator updates the value of the field to aspecified value if the specified value is greater than thecurrent value of the field. The $max operator can comparevalues of different types, using the BSON comparison order.

The $max operator expression has the form:

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

To specify a <field> in an embedded document or in an array, usedot notation.

Behavior

If the field does not exists, the $max operator sets thefield to the specified value.

Examples

Use $max to Compare Numbers

Consider the following document in the collection scores:

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

The highScore for the document currently has the value800. The following operation uses $max to comparethe 800 and the specified value 950 and updates the valueof highScore to 950 since 950 is greater than 800:

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

The scores collection now contains the following modified document:

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

The next operation has no effect since the current value of thefield highScore, i.e. 950, is greater than 870:

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

The document remains unchanged in the scores collection:

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

Use $max to Compare Dates

Consider the following document in the collection tags:

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

The following operation compares the current value of thedateExpired field, i.e.ISODate("2013-10-01T16:38:16.163Z"), with the specified datenew Date("2013-09-30") to determine whether to update thefield:

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

The operation does not update the dateExpired field:

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

See also

db.collection.update(),db.collection.findAndModify()