在 MongoDB 中插入當前日期時間?
要在 MongoDB 中插入當前日期時間,請使用 $setOnInsert 運算子。讓我們首先實現以下查詢以使用文件建立集合
>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")
}以下是如何使用 find() 方法從集合中顯示所有文件的查詢
> db.addCurrentDateTimeDemo.find().pretty();
將生成以下輸出
{
"_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")
}以下是插入當前日期時間的查詢。我們正在插入一條新的 Student 記錄,並在其中插入當前日期時間
> db.addCurrentDateTimeDemo.update( { _id: 1 }, { $set: { StudentName: "Robert" }, $setOnInsert: { StudentAdmissiondate: new Date() } }, { upsert: true } );
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 1 })以下是顯示所有文件的查詢,以驗證是否已插入當前日期時間
> db.addCurrentDateTimeDemo.find().pretty();
將生成以下輸出
{
"_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"
}檢視上面的示例輸出,我們已經插入了當前日期時間,即“2019-03-24T16:21:21.269Z”。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP