2016-11-17 34 views
0

我想從以下文檔中獲取uniq account_numbers。爲什麼mongoTemplate返回數字類型(int)的列值是雙倍的?

{ 
    "_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 = {[email protected]} size = 2815 
0 = {[email protected]} "1626.0" 
1 = {[email protected]} "1670.0" 
2 = {[email protected]} "2936.0" 
3 = {[email protected]} "2295.0" 
4 = {[email protected]} "1010.0" 
5 = {[email protected]} "1471.0" 
6 = {[email protected]} "3333.0" 
7 = {[email protected]} "1469.0" 
8 = {[email protected]} "3445.0" 
9 = {[email protected]} "3193.0" 
10 = {[email protected]} "219.0" 
11 = {[email protected]} "2509.0" 
12 = {[email protected]} "3750.0" 
13 = {[email protected]} "3425.0" 

簡短的問題是 - 如何從文檔中獲取int類型列表以及爲什麼返回雙類型?

這裏是文檔的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; 

回答

2

默認情況下,MongoDB中保存數值雙打:

對於db.coll.save({x: 1})x將被表示(和你的Java驅動程序轉換)爲1.0雙。

要插入一個32位整數,你必須做到:

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

和64個整數,這樣做:

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

底層Java驅動程序也將1保存爲雙(我認爲)通過DBObjectDocument

如果你在你的代碼仔細看看:

mongoTemplate.getCollection("transaction") ...

這裏你落回DBCollection它返回account_number這是一個原始名單,是說,表示爲默認雙。 MongoTemplate映射和轉換在這裏沒有關係:它們用於整個文檔(例如find方法),這裏不是這種情況。

爲了在這裏使用int,你將不得不自己轉換爲List值,或改變account_number存儲值NumberInt

+0

知道了!謝謝。 – amjad

+0

我無法控制集合以更改類型。我只是獲取了值並提取了int值。再次感謝! – amjad

相關問題