1

I'm trying to use a MongoDB shell function, like Date(), on a Jongo driver function to generate a value for my fiedd. The code is the following:

collection.insert( "{ date: Date() }" );

But it doesn't seem to work, any advice ?

Those are the errors lines

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at org.bson.io.PoolOutputBuffer.write(PoolOutputBuffer.java:89)
at org.bson.LazyBSONObject.pipe(LazyBSONObject.java:474)
at org.jongo.bson.BsonDBEncoder.writeObject(BsonDBEncoder.java:39)
at com.mongodb.BSONBinaryWriter.encodeDocument(BSONBinaryWriter.java:339)
at com.mongodb.InsertCommandMessage.writeTheWrites(InsertCommandMessage.java:45)
at com.mongodb.InsertCommandMessage.writeTheWrites(InsertCommandMessage.java:23)
at com.mongodb.BaseWriteCommandMessage.encodeMessageBody(BaseWriteCommandMessage.java:69)
at com.mongodb.BaseWriteCommandMessage.encodeMessageBody(BaseWriteCommandMessage.java:23)
at com.mongodb.RequestMessage.encode(RequestMessage.java:66)
at com.mongodb.BaseWriteCommandMessage.encode(BaseWriteCommandMessage.java:53)
at com.mongodb.DBCollectionImpl.sendWriteCommandMessage(DBCollectionImpl.java:473)
at com.mongodb.DBCollectionImpl.writeWithCommandProtocol(DBCollectionImpl.java:427)
at com.mongodb.DBCollectionImpl.insertWithCommandProtocol(DBCollectionImpl.java:387)
at com.mongodb.DBCollectionImpl.insert(DBCollectionImpl.java:186)
at com.mongodb.DBCollectionImpl.insert(DBCollectionImpl.java:165)
at com.mongodb.DBCollection.insert(DBCollection.java:161)
at com.mongodb.DBCollection.insert(DBCollection.java:107)
at com.mongodb.DBCollection.save(DBCollection.java:966)
at org.jongo.Insert.save(Insert.java:49)
at org.jongo.MongoCollection.save(MongoCollection.java:128)
at learningjongo.DAO.setUp(DAO.java:42)
Guerino Rodella
  • 321
  • 4
  • 16

1 Answers1

3

I suggest you do

collection.insert("{ date: # }", new java.util.Date());

This is equivalent of doing { date: ISODate() } or { date: new Date() }.

Using Date() as you've suggested in your question yields a String, so to mimic that behavior, you would just do something like

collection.insert("{ date: # }", new java.util.Date().toString());

but if you have a choice, I'd suggest you store it as a proper date, and not a String.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • I'd like mongo to do the work, not me. I liked the mongo string for date, it's good enough. – Guerino Rodella Oct 08 '14 at 19:40
  • 1
    I don't think Jongo handles those built in functions. I bet the Jongo developers argue that you should be inserting Java objects using the `#` argument placeholder. – aioobe Oct 08 '14 at 19:42
  • @user3283066, I looked further into this, and AFAICT there's no way of invoking mongo-internal functions from Jongo. Please consider [accepting](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) this answer – aioobe Apr 23 '16 at 20:29