'How to update ISODate to two days later

How to convert a SQL query to mongodb query?

Please write a mongodb query - this is my query in SQL:

UPDATE user  
SET expireIn = DATEADD(DAY, 2, expireIn) 
WHERE phone = '123434574'

I want to add some day to expireIn column.

expireIn field is ISODate and also has a value for the time.



Solution 1:[1]

Welcome Mostafa Asadi, You can do something like this:

db.collection.update({
  phone: "123434574"
},
[
  {
    $set: {
      "expireIn": {
        $dateAdd: {
          startDate: "$expireIn",
          unit: "day",
          amount: 2
        }
      }
    }
  }
],{multi:true})

As you can see on the playground.

The first {} are the matching part, which documents do you want to update. The second part is the updating, here inside [] as this is a pipeline, using the $dateAdd function.

Edit:

with {multi: true} for multiple documents update

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1