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....?
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....?
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/
You can use a pipeline update to achieve this, like so:
Mongo Playground