如何使用MongoDB Java Driver返回正确的数据类型

时间:2015-09-17 08:21:49

标签: java mongodb mongo-java-driver

下面是我正在使用的代码 -

mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("sample");
MongoCollection<Document> imagescollaction = database.getCollection("images");
System.out.println("_id value  : " + imagescollaction.find().first().get("_id"));

程序输出:_id值:0.0

从mongo shell的图像集中输出

db.images.find();

{ "_id" : 0, "height" : 480, "width" : 640, "tags" : [ "dogs", "work"
] }     
{ "_id" : 1, "height" : 480, "width" : 640, "tags" : [ "cats",
"sunrises", "kittens", "travel", "vacation", "work" ] }

我的问题:从mongo shell我可以看到这些值是Long或Integer但是当我使用find方法从java mongo驱动程序查询时它会打印Double。有谁知道为什么会这样。

我正在使用的Mongo驱动程序:3.0.0

1 个答案:

答案 0 :(得分:3)

使用mongoshell插入时,如果要使用整数值,则需要明确说出NumberInt(0)或NumberLong(0)。否则,MongoDB将使用浮点值。

当你在mongodb shell中执行find()时,如果它是一个整数,它也会返回NumberInt(0)或NumberLong(0)。