为什么 mongoTemplate 返回数字类型 (int) 列值是双精度值?

Why mongoTemplate is returning number type (int) column values are as doubles?

我正在尝试从以下文档中获取 uniq account_numbers。

{
    "_id" : ObjectId("5825e49785a4caf2bfa64a2f"),
    "profit" : "",
    "account_number" : 10,
    "m_number" : "",
    "registration_number" : "",
    "page_number" : "",
    "entry_date" : ISODate("2016-04-01T07:35:35Z"),
    "narration" : "By cash",
    "voucher_number" : "",
    "debit_credit" : 6150,
    "account_code" : 2102,
    "created_at" : ISODate("2016-04-01T07:35:35Z"),
    "updated_at" : ISODate("2016-04-01T07:35:35Z"),
    "employee_id" : 0,
    "balance" : 0,
    "credit" : 0,
    "debit" : 0,
    "particulars" : "",
    "since_last" : 0,
    "transaction_type" : 0,
    "voucher_path" : "",
    "branch" : "",
    "auto_voucher_number" : "",
    "check_book_series" : ""
}

account_number 类型是数字,我想使用 Spring Mongo 模板将其获取为 int。

 Query query = new Query();
    query.addCriteria(Criteria.where("account_code").is(accountCode).and("account_number").exists(true));
    return List accounts = mongoTemplate.getCollection("transaction").distinct("account_number", query.getQueryObject());

以上代码正在返回列表帐户。查看调试结果

 accounts = {ArrayList@6192}  size = 2815
 0 = {Double@6217} "1626.0"
 1 = {Double@6218} "1670.0"
 2 = {Double@6219} "2936.0"
 3 = {Double@6220} "2295.0"
 4 = {Double@6221} "1010.0"
 5 = {Double@6222} "1471.0"
 6 = {Double@6223} "3333.0"
 7 = {Double@6224} "1469.0"
 8 = {Double@6225} "3445.0"
 9 = {Double@6226} "3193.0"
 10 = {Double@6227} "219.0"
 11 = {Double@6228} "2509.0"
 12 = {Double@6229} "3750.0"
 13 = {Double@6230} "3425.0"

简短的问题是 - 如何从文档中获取 int 类型列表以及为什么返回 double 类型?

这是文档的 POJO,我可能需要在字段中定义一些东西吗?

@Document(collection = "transaction")
public class Transaction implements Serializable {

    private static final Long serialVersionUID = 1L;

    @Id
    //@GeneratedValue(strategy = GenerationType.IDENTITY)
    @Field(value = "id")
    private String id;

    @Field(value = "account_code")
    private Integer accountCode;

    @Field(value = "account_number")
    private Integer accountNumber;

默认情况下 MongoDB 将数值保存为双精度:

对于 db.coll.save({x: 1})x 将表示(并由您的 Java 驱动程序转换)为 1.0 double.

要插入 32 位整数,您必须执行以下操作:

db.coll.save({x: NumberInt(1)})

对于 64 个整数,执行:

db.coll.save({x: NumberLong(1)})

底层 Java 驱动程序还将通过 DBObjectDocument.

1 保存为双倍(我认为)

如果您仔细查看您的代码:

mongoTemplate.getCollection("transaction")...

在这里您将回到 DBCollection,其中 returns 是 account_number 的原始列表,如前所述,默认情况下表示为 double。 MongoTemplate 映射和转换在这里不相关:它们用于整个文档(例如 find 方法),这里不是这种情况。

为了在这里使用int,您必须自己转换为List值,或者将account_number存储值更改为NumberInt.