4

I'm trying to craft a new Date value into a projection within a reactivemongo aggregate pipeline.

I have seen other examples where people create this within the mongo shell, like this:

db.runCommand({
    "aggregate" : "collectionName", "pipeline": [
       { $project: { exampleDate: new Date() } } 
    ]
})

The problem lies in the new Date(). With reactivemongo the projection would be a Project object:

Project( ("exampleDate", BSONValue) )

where the BSONValue can be a BSONString. But that results in mongoDB ignoring such string, since the result will be:

{ "aggregate" : "collectionName", "pipeline": [ { $project: { exampleDate: "new Date()" } } ] }

Is there any way to insert the new Date() without the quotes?

P.S.: I've also tried using BSONDateTime(0) But this results in:

{ $date: 0 }

Which makes mongoDB throw an invalid $date operator exception.

Reid Spencer
  • 2,776
  • 28
  • 37
Bilk
  • 418
  • 6
  • 19

1 Answers1

0

Since the default constructor of the java.util.Date class gives the time of the call to the constructor (aka "now"), it seems you are interested in constructing a BSONDateTime with the same "now" time. The argument to BSONDateTime should be a Long value that contains the UTC time in milliseconds. You can get that from java.lang.System.currentTimeMillis or from the java.util.Date.getTime method. So, I think what you want is:

Project( ("exampleDate", BSONDateTime(System.currentTimeMillis()) )

or

val now = new java.util.Date()
Project( ("exampleDate", BSONDateTime(now.getTime) )
Reid Spencer
  • 2,776
  • 28
  • 37
  • Unfortunately that won't work, because mongo throws an invalid `$date` operator exception. – Bilk Jan 16 '15 at 12:03
  • You would need to share the exact code that is producing this for further diagnosis. Could you whittle the problem down into a small project and put it on GitHub? If so, I can probably figure out what the issue is. – Reid Spencer Jan 16 '15 at 13:09
  • @bILK did you find the solution for it , adding new Date() in projection stage – Kiran Sunkari May 24 '17 at 04:41