Để chèn ngày giờ hiện tại trong MongoDB, hãy sử dụng toán tử $ setOnInsert. Trước tiên, hãy để chúng tôi triển khai truy vấn sau để tạo một bộ sưu tập với các tài liệu
>db.addCurrentDateTimeDemo.insertOne({"StudentName":"John","StudentAdmissionDate":new Date("2012-01-21") });
{
"acknowledged" : true,
"insertedId" : ObjectId("5c97ae45330fd0aa0d2fe49f")
}
>db.addCurrentDateTimeDemo.insertOne({"StudentName":"Carol","StudentAdmissionDate":new Date("2013-05-24") });
{
"acknowledged" : true,
"insertedId" : ObjectId("5c97ae54330fd0aa0d2fe4a0")
}
>db.addCurrentDateTimeDemo.insertOne({"StudentName":"Carol","StudentAdmissionDate":new Date("2019-07-26") });
{
"acknowledged" : true,
"insertedId" : ObjectId("5c97ae5f330fd0aa0d2fe4a1")
} Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find ()
> db.addCurrentDateTimeDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5c97ae45330fd0aa0d2fe49f"),
"StudentName" : "John",
"StudentAdmissionDate" : ISODate("2012-01-21T00:00:00Z")
}
{
"_id" : ObjectId("5c97ae54330fd0aa0d2fe4a0"),
"StudentName" : "Carol",
"StudentAdmissionDate" : ISODate("2013-05-24T00:00:00Z")
}
{
"_id" : ObjectId("5c97ae5f330fd0aa0d2fe4a1"),
"StudentName" : "Carol",
"StudentAdmissionDate" : ISODate("2019-07-26T00:00:00Z")
} Sau đây là truy vấn để chèn ngày giờ hiện tại. Chúng tôi đang chèn một hồ sơ Sinh viên mới và trong đó thời gian ngày hiện tại
> db.addCurrentDateTimeDemo.update( { _id: 1 }, { $set: { StudentName: "Robert" }, $setOnInsert: { StudentAdmissiondate: new Date() } }, { upsert: true } );
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 1 }) Sau đây là truy vấn để hiển thị tất cả các tài liệu để xác minh rằng ngày giờ hiện tại đã được chèn hay chưa
> db.addCurrentDateTimeDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5c97ae45330fd0aa0d2fe49f"),
"StudentName" : "John",
"StudentAdmissionDate" : ISODate("2012-01-21T00:00:00Z")
}
{
"_id" : ObjectId("5c97ae54330fd0aa0d2fe4a0"),
"StudentName" : "Carol",
"StudentAdmissionDate" : ISODate("2013-05-24T00:00:00Z")
}
{
"_id" : ObjectId("5c97ae5f330fd0aa0d2fe4a1"),
"StudentName" : "Carol",
"StudentAdmissionDate" : ISODate("2019-07-26T00:00:00Z")
}
{
"_id" : 1,
"StudentAdmissiondate" : ISODate("2019-03-24T16:21:21.269Z"),
"StudentName" : "Robert"
} Nhìn vào kết quả mẫu ở trên, chúng tôi đã chèn thời gian ngày hiện tại, là “2019-03-24T16:21:21.269Z”.