2

I'm trying to use the group aggregation.

I have documents of the following structure in my mongodb:

{ "_id" : ObjectId("4ddcdc9ab4d8a3a90345508e"), "vehicleId" : "1", "timestamp" : ISODate("2011-05-25T10:40:25.856Z"), "speed" : 1 }

{ "_id" : ObjectId("4ddcdc9ab4d8a3a90345508f"), "vehicleId" : "2", "timestamp" : ISODate("2011-05-25T10:40:26.232Z"), "speed" : 2 }

In a test, I want to get the latest speed per vehicleId, i.e. I'm doing the following:

val key = MongoDBObject("vehicleId" -> true)
val cond = MongoDBObject.empty
val initial = MongoDBObject("timestamp" -> 0)

val reduce =
  """function(doc, prev) {
       if (doc.timestamp > prev.timestamp) {
          prev.speed = doc.speed;
          prev.timestamp = doc.timestamp;
       }
     }"""

val groupedSpeed = collection.group(key, cond, initial, reduce)

for (dbObject: DBObject <- groupedSpeed) {
  println(dbObject.toString)

The weird thing is that in the collection groupedSpeed, the field speed is not an Int anymore:

{ "vehicleId" : "2" , "timestamp" : { "$date" : "2011-05-25T10:40:49Z"} , "speed" : 2.0}
{ "vehicleId" : "1" , "timestamp" : { "$date" : "2011-05-25T10:40:49Z"} , "speed" : 1.0}

Did I miss something? I'm using casbah 2.1.2.

Cheers, Christian

[UPDATE] Looks like this is normal in javascript and bson, see here: casbah mailing list

Christian
  • 4,543
  • 1
  • 22
  • 31

1 Answers1

0

Javascript represents all numeric values as doubles.

You might want to extend your application logic so whenever a new document is inserted, in a separate collection you also update the max speed for that vehicle, so you never have to do group queries.

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176