Để tự động gán thời gian hiện tại khi **insert mới** (upsert), dùng toán tử $setOnInsert kết hợp upsert: true. Trường này chỉ được set khi document được tạo mới, không ảnh hưởng khi update document đã tồn tại.
Cú pháp
db.collection.update(
{ },
{
$set: { ... }, // Cập nhật thường (chạy cả insert và update)
$setOnInsert: { createdAt: new Date() } // Chỉ chạy khi insert mới
},
{ upsert: true }
);
Ví dụ minh họa
Tạo collection addCurrentDateTimeDemo với dữ liệu ban đầu:
> db.addCurrentDateTimeDemo.insertOne({ "StudentName": "John", "StudentAdmissionDate": new Date("2012-01-21") });
> db.addCurrentDateTimeDemo.insertOne({ "StudentName": "Carol", "StudentAdmissionDate": new Date("2013-05-24") });
> db.addCurrentDateTimeDemo.insertOne({ "StudentName": "Carol", "StudentAdmissionDate": new Date("2019-07-26") });
Hiển thị:
> db.addCurrentDateTimeDemo.find().pretty();
Kết quả:
{ "_id" : ObjectId("..."), "StudentName" : "John", "StudentAdmissionDate" : ISODate("2012-01-21T00:00:00Z") }
{ "_id" : ObjectId("..."), "StudentName" : "Carol", "StudentAdmissionDate" : ISODate("2013-05-24T00:00:00Z") }
{ "_id" : ObjectId("..."), "StudentName" : "Carol", "StudentAdmissionDate" : ISODate("2019-07-26T00:00:00Z") }
Upsert document mới với $setOnInsert (tự gán datetime hiện tại)
> db.addCurrentDateTimeDemo.update(
{ _id: 1 }, // Query: tìm _id = 1 (chưa tồn tại)
{
$set: { StudentName: "Robert" }, // Luôn set
$setOnInsert: { StudentAdmissiondate: new Date() } // Chỉ set khi insert
},
{ upsert: true }
);
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 1 })
Kiểm tra:
> db.addCurrentDateTimeDemo.find().pretty();
Kết quả (document mới có StudentAdmissiondate = thời điểm chạy lệnh):
{ "_id" : ObjectId("..."), "StudentName" : "John", "StudentAdmissionDate" : ISODate("2012-01-21T00:00:00Z") }
{ "_id" : ObjectId("..."), "StudentName" : "Carol", "StudentAdmissionDate" : ISODate("2013-05-24T00:00:00Z") }
{ "_id" : ObjectId("..."), "StudentName" : "Carol", "StudentAdmissionDate" : ISODate("2019-07-26T00:00:00Z") }
{ "_id" : 1, "StudentAdmissiondate" : ISODate("2019-03-24T16:21:21.269Z"), "StudentName" : "Robert" }
Các cách khác để set datetime hiện tại
| Phương pháp | Cú pháp | Đặc điểm |
|---|---|---|
| $currentDate | { $currentDate: { createdAt: true } } | Set timestamp server, dùng trong $set/$setOnInsert. Hỗ trợ { $type: "timestamp" } cho BSON Timestamp. |
| Default value (Schema) | MongoDB 4.4+: db.createCollection("c", { validator: { $jsonSchema: { properties: { createdAt: { bsonType: "date", default: "$$NOW" } } } } }) | Tự động set khi insert, không cần code ứng dụng. Chỉ dùng cho insert, không cho upsert. |
| Application layer | Driver: new Date() (Node.js), datetime.utcnow() (Python) | Kiểm soát chính xác, dễ test, không phụ thuộc server time. |
Lưu ý
$setOnInsertchỉ hoạt động vớiupsert: true.- Nếu document đã tồn tại,
$setOnInsertbị bỏ qua,$setvẫn chạy. - Dùng
new Date()trong shell trả về **ISODate** (UTC).