Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a document with date in mongo?

We are trying to insert a document with the current date as it's field. We are writing in java using eclipse plugin for mongodb. We want to execute the Date() command of mongo to get the date from mongo and not from java.

How can I execute this mongo query?

db.example.insert({"date":new Date()})

I found this question in a previews question but the answer was not helpful

Link

like image 875
itaied Avatar asked Jun 30 '14 05:06

itaied


People also ask

How do I add a timestamp in MongoDB?

In MongoDB, a special timestamp type is provided by BSON for the internal use and is not connected with the MongoDB's regular data type for Data. The Timestamp for internal use is of 64 bit of value, where this 64 bit is a combination of two 32 bit values.

How do I create a date in MongoDB?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.


3 Answers

The standard driver takes java.util.date types and serializes as BSON dates. So with a collection object to "example"

Date now = new Date();

BasicDBObject timeNow = new BasicDBObject("date", now);
example.insert(timeNow);

If you are looking for a way to use the "server" time in operations, there is the $currentDate operator, but this works with "updates", so you would want an "upsert" operation:

 BasicDBObject query = new BasicDBObect();
 BasicDBObject update = new BasicDBObject("$currentDate",
     new BasicDBObject("date", true)
 );

 example.update(query,update,true,false);

Since that actually is an update statement, you need to be careful that you are not actually matching any documents if you intend this to be an insert only. So it would be best to make sure your "query" contains unique information, such as a newly generated _id or something equally unique.

like image 50
Neil Lunn Avatar answered Oct 07 '22 11:10

Neil Lunn


You can do it trying something like this:

db.example.insert({"date":ISODate("2016-03-03T08:00:00.000")});
like image 42
maikelsperandio Avatar answered Oct 07 '22 11:10

maikelsperandio


Use this:

db.example.insert({"date":new Date(Date.now())});
like image 30
Devesh Kumar Avatar answered Oct 07 '22 11:10

Devesh Kumar