要在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") }
以下是插入当前日期时间的查询。我们正在插入新的学生记录,并且在当前日期时间内
> 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”。