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.

Updated on: 2026-03-15T03:10:28+05:30

196 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements