在 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