Inserting the current datetime in MongoDB?


To insert current datetime in MongoDB, use the $setOnInsert operator. Let us first implement the following query to create a collection with documents

>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")
}

Following is the query to display all documents from a collection with the help of find() method

> db.addCurrentDateTimeDemo.find().pretty();

This will produce the following output

{
   "_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")
}

Following is the query to insert current date time. We are inserting a new Student record and within that the current date time

> db.addCurrentDateTimeDemo.update( { _id: 1 }, { $set: { StudentName: "Robert" }, $setOnInsert: { StudentAdmissiondate: new Date() } }, { upsert: true } );
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 1 })

Following is the query to display all documents in order to verify that the current date time is inserted or not

> db.addCurrentDateTimeDemo.find().pretty();

This will produce the following output

{
   "_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"
}

Look at the above sample output, we have inserted current date time, which is “2019-03-24T16:21:21.269Z”.

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements