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
Long terms interchangeably in this article.
2. MongoDB Int64
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.,
- mongo Shell mode. The MongoDB internal JSON parser and the mongo shell can parse this mode.
2.1. MongoDB save Int64 data type
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
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
Long type to a document in a sample collection.
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.
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
2.3. MongoDB query Int64 in Java
Query query = new Query(Criteria.where("storeId").is(Long.parseLong("12712239838493442")); mongoTemplate.exists(query, Sample.class);
To sum up, we have learned to query Long values stored in MongoDB documents.