mercredi 11 mars 2015

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)




Aucun commentaire:

Enregistrer un commentaire