Minus a day from date in MongoDb

69 Views Asked by At

I want MongoDB query to minus a day from existing date in a column and update the same.

query to update a date like original date = '2024-12-24T18:30:32' updated date = '2024-12-23T18:30:32' and how to execute the query on terminal also....?

2

There are 2 best solutions below

0
Tom Slabbaert On

You can use a pipeline update to achieve this, like so:

db.collection.update({
  "_id": 1
},
[
  {
    "$set": {
      "date": {
        $subtract: [
          "$date",
          1000 * 60 * 60 * 24 //one day in milliseconds
        ]
      }
    }
  }
])

Mongo Playground

1
Sumeet Shukla On

Go to the terminal and use mongosh command to login to DB as below:

mongosh "mongodb+srv://<username>:<password>@<cluster_name>.example.mongodb.net"

Connect to appropriate DB using show dbs and use <db_name> command. And use $dateSubtract expression as below:

db.collection.update({
    "_id": ObjectId("<dummy_id>")
},
[
    {
    $set: {
        date: {
            $dateSubtract: {
                startDate: "$date", // ISODate("2024-12-24T18:30:32"),
                unit: "day",
                amount: 1
                }
            }
        }
    }
])

Syntax in general for $dateSubtract is:

{
    $dateSubtract: {
        startDate: <Expression>,
        unit: <Expression>,
        amount: <Expression>,
        timezone: <tzExpression>
    }
}

Refer below links for more details:

https://www.mongodb.com/docs/v4.4/mongo/#start-the-mongo-shell-and-connect-to-mongodb

https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateSubtract/