Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Update field if new value is greater

Tags:

mongodb

How to update a field in a MongoDB document only if the new value is greater then the current value?

Any solution?

db.report.update(
    { _id: 1234 },
    {
      $setIfGreater: {
        A: 10
      }
   })
like image 431
Alain1405 Avatar asked Mar 04 '15 16:03

Alain1405


People also ask

Is it possible to update MongoDB field using value of another field?

The way we do this is by $project ing our documents and using the $concat string aggregation operator to return the concatenated string. You then iterate the cursor and use the $set update operator to add the new field to your documents using bulk operations for maximum efficiency.

How do I increment a field in MongoDB?

In MongoDB, the $inc operator is used to increment the value of a field by a specified amount. The $inc operator adds as a new field when the specified field does not exist, and sets the field to the specified amount. The $inc accepts positive and negative value as an incremental amount.


1 Answers

You can use the $max operator to do this:

db.report.update(
    { _id: 1234 },
    {
      $inc: { A: 5 },
      $set: {
        B: "ABC123",
      }
      $max: {
        C: 10
      }
    })

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.

like image 199
JohnnyHK Avatar answered Sep 19 '22 08:09

JohnnyHK