$min

Definition

  • $min
  • The $min updates the value of the field to a specifiedvalue if the specified value is less than the current value ofthe field. The $min operator can compare values ofdifferent types, using the BSON comparison order.
  1. { $min: { <field1>: <value1>, ... } }

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

Behavior

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

For comparisons between values of different types, such as a number anda null, $min uses the BSON comparison order.

Examples

Use $min to Compare Numbers

Consider the following document in the collection scores:

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

The lowScore for the document currently has the value200. The following operation uses $min to compare200 to the specified value 150 and updates the value oflowScore to 150 since 150 is less than 200:

  1. db.scores.update( { _id: 1 }, { $min: { lowScore: 150 } } )

The scores collection now contains the following modified document:

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

The next operation has no effect since the current value of thefield lowScore, i.e 150, is less than 250:

  1. db.scores.update( { _id: 1 }, { $min: { lowScore: 250 } } )

The document remains unchanged in the scores collection:

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

Use $min 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:16Z")
  6. }

The following operation compares the current value of thedateEntered field, i.e. ISODate("2013-10-01T05:00:00Z"),with the specified date new Date("2013-09-25") to determinewhether to update the field:

  1. db.tags.update(
  2. { _id: 1 },
  3. { $min: { dateEntered: new Date("2013-09-25") } }
  4. )

The operation updates the dateEntered field:

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

See also

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