How to insert a document with date in mongo?

前端 未结 3 1909
逝去的感伤
逝去的感伤 2020-12-02 01:47

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()

相关标签:
3条回答
  • 2020-12-02 02:05

    You can do it trying something like this:

    db.example.insert({"date":ISODate("2016-03-03T08:00:00.000")});
    
    0 讨论(0)
  • 2020-12-02 02:19

    Use this:

    db.example.insert({"date":new Date(Date.now())});
    
    0 讨论(0)
  • 2020-12-02 02:21

    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.

    0 讨论(0)
提交回复
热议问题