skip to Main Content

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

Answers


  1. 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

    Login or Signup to reply.
  2. 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:

    {
        $dateSubtract: {
            startDate: ISODate("2024-12-24T18:30:32"),
            unit: "day",
            amount: 1
        }
    }
    

    Syntax in general:

    {
        $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/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search