简体   繁体   中英

How to return the correct datatype with MongoDB Java Driver

below is the code i am using -

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"));

output of program : _id value : 0.0

out put from image collection from 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" ] }

My question : from the mongo shell i can see those values are Long or Integer but when i am querying from the java mongo driver using find method it is printing Double. Does anybody know why is this happening.

Mongo driver i am using : 3.0.0

When inserting using mongoshell, you need to explicitly say NumberInt(0) or NumberLong(0) if you want to have integer values. Otherwise, MongoDB will use floating point values.

When you do a find() in mongodb shell, it will also return NumberInt(0) or NumberLong(0) if it is an integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM