Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo insert $currentDate in Java Driver

I've got a question about $currentDate What is the best way to insert a document in mongo db so that it contains the "server time" (like ''now()'' in some RDBMSs) using the Java Driver?

For example, lest say I have a document like:

{
     name : "John",
     birthday : <$currentDate_goes_here>
}

What I want is to insert the document so that the evaluation of the date would be done by mongo server at the time of insertion on the server side.

This is critical because our servers might not be totally synchronized and there is a need to have the time we can rely on (for example the time on mongo server).

I'm using a standard java driver for mongo, so any code snippet in Java will be more than welcome.

This is what I've tried so far

 MongoClient mongoClient = new MongoClient();
 DB sampleDB = mongoClient.getDB("sampleDB");
 BasicDBObject update = 
          new BasicDBObject("$set", new     BasicDBObject("name","john")
              .append("$currentDate", new BasicDBObject("birthday",true)));
sampleDB.getCollection("col1").insert(update);

This thing fails on the following exception:

java.lang.IllegalArgumentException: Document field names can't start with '$' (Bad Key: '$set') at com.mongodb.DBCollection.validateKey(DBCollection.java:1845) at com.mongodb.DBCollection._checkKeys(DBCollection.java:1803) at com.mongodb.DBCollection._checkObject(DBCollection.java:1790) at com.mongodb.DBCollectionImpl.applyRulesForInsert(DBCollectionImpl.java:392) at com.mongodb.DBCollectionImpl.insertWithCommandProtocol(DBCollectionImpl.java:381) at com.mongodb.DBCollectionImpl.insert(DBCollectionImpl.java:186) at com.mongodb.DBCollectionImpl.insert(DBCollectionImpl.java:165) at com.mongodb.DBCollection.insert(DBCollection.java:93) at com.mongodb.DBCollection.insert(DBCollection.java:78) at com.mongodb.DBCollection.insert(DBCollection.java:120)

like image 538
Mark Bramnik Avatar asked Oct 24 '25 13:10

Mark Bramnik


1 Answers

In which case the answer is fairly simple. It is really about serializing from java BasicDBObject classes to the basic MongoDB interpretation. Without respect to your actual "query" document the "update" document part of your statement should be:

    BasicDBObject update = new BasicDBObject("$set", new BasicDBObject("name","john")
        .append("$currentDate", new BasicDBObject("birthrhday",true))
    ;

Which will indeed use the "server time" at the point of "update insertion" or "modification" with respect to the $currentDate modifier as used.

Just to be clear here, you don't use the .insert() method but an "upsert"operation with .insert(). The "query" and "update" syntax applies. Also see the $setOnInsert operator for specifically not modifying existing documents.

like image 142
Neil Lunn Avatar answered Oct 27 '25 03:10

Neil Lunn