Document.parse is failing for new Date(new Date().getTime())

Hello Team

I executed following in mongodb successfully

db.runCommand( { count : ‘name’, query: { createDate: { $gte: new Date(new Date().getTime() - 2 * 1000 * 60 * 60 ) } } });

now I’m trying to execute the same in Spring mongoTemplate.executeCommand and get failed with following exception.

org.bson.json.JsonParseException: JSON reader expected an integer or a string but found ‘new’.

I noticed the problem is with Document.parse (inside montoTemplate.executeMethod) is failing to parse below

new Date(new Date().getTime() - 2 * 1000 * 60 * 60 )

How to get successful for the above section in Document.parse.

In the runCommand(), the date operations are not in quotes. They are evaluated by the mongo shell before being sent to the server.

You have to do the same in your Java code.

‘new Date(new Date().getTime() - 2 * 1000 * 60 * 60 )’ like this ?

I’m just googling and seems like we could not pass ‘new Date().getTime()’ things as bson values. Is that right ?

reference:- https://jira.mongodb.org/browse/JAVA-3316

No. Not like this:

Not inside quotes. Just like your runCommand(). The new Date(…) expression has to be executed by Java. You put the result of the expression in your document. Alternatively you may use:

Got it… Is there any way I can say get 2 hour before records from Collection.

I should not do any Java manipulations on the query. I should get the BSON query as string and execute it from mongoTemplate.executeCommand.

I am not sure but the following might work:

Below mongo commands are not working in mongodb , no errors but return 0 results(expect some records should return).

db.runCommand( { count : ‘name’, query: { createDate: { $gte: { $subtract: [ ‘$createdDate’ , 10 * 1000 * 60 * 60 ]} } } });

db.runCommand( { count : ‘name’, query: { createDate: { $gte: { $subtract: [ ‘$$NOW’ , 10 * 1000 * 60 * 60 ]} } } });

I am not familiar enough with runCommand() to help you further with this.