Để tăng ngày trong JavaScript trước khi cập nhật MongoDB, dùng Date object: new Date() lấy thời điểm hiện tại, getDate() lấy ngày, setDate() set ngày mới (tự xử lý chuyển tháng/năm). Sau đó dùng $set hoặc $currentDate để cập nhật.
Dữ liệu mẫu
> db.demo168.insertOne({"DueDate":null});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3695ae9e4f06af551997d6") }
Xem dữ liệu
> db.demo168.find();
{ "_id" : ObjectId("5e3695ae9e4f06af551997d6"), "DueDate" : null }
Tính ngày mai và ngày mốt trong JS, cập nhật MongoDB
> var t = new Date();
> t.setDate(t.getDate()+1); // ngày mai
1580722089017
> var dat = new Date();
> dat.setDate(dat.getDate()+2); // ngày mốt
1580808489085
> db.demo168.update(
... { "_id": ObjectId("5e3695ae9e4f06af551997d6") },
... { "$currentDate": { "DueDate": true }, "$set": { "DueDate1": t, "DueDate2": dat } }
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Kết quả
> db.demo168.find();
{ "_id" : ObjectId("5e3695ae9e4f06af551997d6"), "DueDate" : ISODate("2020-02-02T09:28:09.308Z"), "DueDate1" : ISODate("2020-02-03T09:28:09.017Z"), "DueDate2" : ISODate("2020-02-04T09:28:09.085Z") }
Giải thích:
$currentDate: {DueDate: true}setDueDate= thời gian server hiện tại (ISODate).$setgán giá trị Date object JS (t,dat) đã tính toán trước.- Lưu ý:
setDatesửa đổi object Date gốc (mutable). Nên clone nếu cần giữ nguyên:var t = new Date(); t.setDate(t.getDate()+1);. - MongoDB 5.0+ có
$dateAddtrong aggregation/update pipeline để tính toán ngày phía server.