使用组聚合时数据类型从 Int 更改为 Float
我正在尝试使用组聚合。
我的 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 }
在测试中,我想获取每个vehicleId的最新速度,即我 执行以下操作:
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)
奇怪的是,在集合 groupedSpeed 中,字段 speed 不再是 Int:
{ "vehicleId" : "2" , "timestamp" : { "$date" : "2011-05-25T10:40:49Z"} , "speed" : 2.0}
{ "vehicleId" : "1" , "timestamp" : { "$date" : "2011-05-25T10:40:49Z"} , "speed" : 1.0}
我错过了什么吗?我正在使用 casbah 2.1.2。
干杯, Christian
[更新] 看起来这在 javascript 和 bson 中是正常的,请参见此处:casbah 邮件列表
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Javascript 将所有数值表示为双精度值。
您可能希望扩展应用程序逻辑,以便每当插入新文档时,您还可以在单独的集合中更新该车辆的最大速度,这样您就不必进行组查询。
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.