簡體   English   中英

MongoDB: class java.lang.Double cannot be cast to class java.lang.Long

[英]MongoDB: class java.lang.Double cannot be cast to class java.lang.Long

我們使用 MongoDB 得到這個錯誤:

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 合作過。

這種錯誤很少見,但如果發生,它是可重現的。

可能是什么原因?

問題可能是任何指示的字段實際上都存儲為Double而不是Long

Document class 的源代碼中可以看到,在getLong方法中可以找到以下內容:

return (Long) get(key);

這個強制轉換是導致 Mongo 驅動程序報告錯誤的原因。

您的某些時間戳是否可能是使用 Javascript 和 NodeJS 創建的,也許是使用 Mongo shell 創建的? 如果是這種情況,根據您創建時間戳的方式,由於數字在 Javascript 中的表示方式,您的字段值可能會以double精度形式插入。

mongo shell文檔指出

mongo shell 默認將所有數字視為浮點值。

並且

默認情況下,mongo shell 將所有數字視為 64 位浮點double精度值。

該問題已在此問題中的 SO 中記錄。 它已經過時了,但它可能是對您問題的可能解釋。

這篇文章雖然也很過時並且與您的問題沒有直接關系,但提供了一些額外的背景。

If the database contains a mix of integer and floating point types for a particular field, and you want to treat them all as long in your Java code, you could use the java.lang.Number class, like so:

  trashDoc.get("_created", Number.class).longValue()

由於DoubleIntegerLong都擴展了Number ,此代碼將用於從任何數字字段中提取 long 值。 請記住,如果值是 Double,它將丟棄 Double 的小數部分,即

    Document d = new Document()
            .append("_created", 4.2);
    System.out.println(d.get("_created", Number.class).longValue());

將打印4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM