简体   繁体   中英

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

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.

你可以尝试这样的事情:

db.example.insert({"date":ISODate("2016-03-03T08:00:00.000")});

用这个:

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

There is a key difference I noted when using Date() as follows.

{ dateWhenCreated : Date() }

vs

{ dateWhenCreated : new Date() }

Notice the "new" keyword in the second usage. Whereas the first usage loads the data "as a string", the second one loads date as a field with date data type.

This might impact your sorting capability - dates stored as strings don't get sorted the same way as dates stored as dates.

Per the mongodb documentation here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM