
1. Overview
In this article, we will learn to query Int64 fields in the MongoDB database.
The Int64 BSON data type is a Long class for representing a 64-bit two’s-complement integer value, which faithfully simulates the behavior of a Java “Long”. We would use both Int64 and Long terms interchangeably in this article.
2. MongoDB Int64
MongoDB stores documents internally in BSON?(Binary?JSON). BSON has two integer types, a 32-bit signed integer type called?INT?and a 64-bit signed integer type called?LONG.?
JSON?can only represent a subset of the data types supported by?BSON. To represent a NumberLong 64-bit integer BSON data type in a JSON document, we use associated JSON representations in Strict mode?and?mongo?Shell mode formats:
- Strict mode. Strict mode representations of BSON types conform to the?JSON RFC. Any JSON parser can parse these strict mode representations as key/value pairs; however, only the MongoDB internal JSON parser recognizes the type information conveyed by the format. i.e.,
NumberLong - mongo?Shell mode. The MongoDB internal JSON parser and the?mongo?shell can parse this mode.

2.1. MongoDB save Int64 data type
The?mongo?shell treats all numbers as floating-point values by default.
To force the mongo parser to treat the provided value as a 64-bit Long type, you must use NumberLong() wrapper.
MongoDB internal parser recognizes the type information by looking at the wrapper.
You must include the value within quotation marks or it will be interpreted as a floating point number, resulting in a loss of accuracy.
Let’s add the storeId of Long type to a document in a sample collection.
Here, used numberLong wrapper to wrap a Long value (64-bit integer) and notice the quotation marks around the value 12712239838493884. If you don’t use quotation marks, the MongoDB parser would interpret it as a floating point number.
The storeId saved as Int64 data type in MongoDB.
2.2. MongoDB query Int64
Let’s query the saved document with storeId. You must use the NumberLong wrapper to search using the storeId.

2.3. MongoDB query Int64 in Java
Query query = new Query(Criteria.where("storeId").is(Long.parseLong("12712239838493442"));
mongoTemplate.exists(query, Sample.class); 3. Conclusion
To sum up, we have learned to query Long values stored in MongoDB documents.