MongoDB:类 java.lang.Double 不能转换为类 java.lang.Long [英] MongoDB: class java.lang.Double cannot be cast to class java.lang.Long

查看:73
本文介绍了MongoDB:类 java.lang.Double 不能转换为类 java.lang.Long的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用 MongoDB,但出现此错误:

We use MongoDB and we get this error:

class java.lang.Double cannot be cast to class java.lang.Long (java.lang.Double and java.lang.Long are in module java.base of loader ‘bootstrap’)

堆栈跟踪:

{
  "file": "Document.java",
  "method": "getLong",
  "line": 266,
  "exact": false,
  "location": "bson-3.11.0.jar",
  "class": "org.bson.Document",
  "version": "?"
},
{
  "file": "Util.kt",
  "method": "determineLastChanged",
  "line": 11,
  "exact": false,
  "location": "foobar-backend-persist-2020.47.5.jar",
  "class": "com.foobar.persist.trash.UtilKt",
  "version": "?"
},

我们的代码:

// com.foobar.persist.trash.UtilKt

import org.bson.Document

internal fun determineLastChanged(trashDoc: Document): Long {
  return trashDoc.getLong("_touched")
    ?: trashDoc.getLong("_created")
    ?: trashDoc.getDocument("_trash")?.getLong("deletedAt")
    ?: throw InternalTrashException("trash item without timestamp")
}

我知道 Java,但我是 MongoDB 的新手.我过去使用过 SQL.

I know Java, but I am new to MongoDB. I worked with SQL in the past.

此错误很少见,但如果发生,则可重现.

This error is rare, but if it happens, it is reproducible.

可能是什么原因?

推荐答案

问题可能是任何指示的字段实际上存储为 Double 而不是 Long.

The problem probably is that any of the indicated fields is actually stored as Double instead of Long.

正如您在 源代码Document类,在getLong方法中可以找到:

As you can see in the source code of the Document class, in the getLong method you can find the following:

return (Long) get(key);

此演员是导致 Mongo 驱动程序报告错误的演员.

This cast is the one that is causing the error reported by the Mongo driver.

您的某些时间戳是否可能是使用 Javascript 和 NodeJS 创建的,也许是使用 Mongo shell 创建的?如果是这种情况,根据您创建时间戳的方式,由于数字在 Javascript 中的表示方式,您的字段值可能会插入为 double.

Is it possible that some of your timestamps are created with Javascript and NodeJS, perhaps with the Mongo shell? If that is the case, depending on how you create the timestamp, the value of your field could be inserted as double due to the way numbers are represented in Javascript.

mongo shell 文档说明:

The mongo shell documentation indicates:

默认情况下,mongo shell 将所有数字视为浮点值.

The mongo shell treats all numbers as floating-point values by default.

:

默认情况下,mongo shell 将所有数字视为 64 位浮点 double 值.

The mongo shell treats all numbers as 64-bit floating-point double values by default.

此问题已在此处记录在此 问题.它已经过时了,但可以解释您的问题.

The issue has been documented here in SO in this question. It is quite dated, but it could be a possible explanation of your problem.

这篇文章,虽然也很过时与您的问题没有直接关系,提供一些额外的背景.

This article, although also quite dated and not directly related with your problem, provides some additional background.

这篇关于MongoDB:类 java.lang.Double 不能转换为类 java.lang.Long的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆