Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Can we work MongoDB findOne() with long type _id?
Yes, MongoDB's findOne() method works with NumberLong data type for _id fields. Use NumberLong() to wrap long integer values when storing and querying documents with numeric _id values that exceed JavaScript's safe integer range.
Syntax
db.collection.findOne({_id: NumberLong("longValue")});
Create Sample Data
Let's create a collection with NumberLong _id values ?
db.demo618.insertMany([
{_id: NumberLong("6336366454"), Name: "Chris"},
{_id: NumberLong("6336366455"), Name: "David"},
{_id: NumberLong("6336366456"), Name: "Bob"}
]);
{
"acknowledged": true,
"insertedIds": [
NumberLong("6336366454"),
NumberLong("6336366455"),
NumberLong("6336366456")
]
}
Display all documents from the collection ?
db.demo618.find();
{ "_id": NumberLong("6336366454"), "Name": "Chris" }
{ "_id": NumberLong("6336366455"), "Name": "David" }
{ "_id": NumberLong("6336366456"), "Name": "Bob" }
Example: Using findOne() with NumberLong _id
Query to find a specific document using NumberLong _id ?
db.demo618.findOne({_id: NumberLong("6336366454")});
{ "_id": NumberLong("6336366454"), "Name": "Chris" }
Key Points
-
NumberLong()is required for integer values exceeding JavaScript's safe integer range (2^53 - 1). - Both storage and query operations must use the same
NumberLong()wrapper for consistency.
Conclusion
MongoDB's findOne() method fully supports NumberLong _id fields. Always wrap long integer values with NumberLong() for both insertion and querying to ensure accurate data handling.
Advertisements
