How do I find all documents with a field that is NaN in MongoDB?

To find all documents with a field that is NaN in MongoDB, use the $eq operator or direct comparison with NaN value in your query.

Syntax

db.collection.find({ fieldName: NaN });

Or using the $eq operator:

db.collection.find({ fieldName: { $eq: NaN } });

Create Sample Data

First, let's create a collection with documents containing various numerical values including NaN ?

db.nanDemo.insertMany([
    { "Score": 0/0 },        // NaN
    { "Score": 10/5 },       // 2
    { "Score": 20/0 },       // Infinity
    { "Score": 0/20 }        // 0
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5ca251a26304881c5ce84b8a"),
        ObjectId("5ca2520e6304881c5ce84b8b"),
        ObjectId("5ca252156304881c5ce84b8c"),
        ObjectId("5ca2521e6304881c5ce84b8d")
    ]
}

View All Documents

Let's display all documents to see the data structure ?

db.nanDemo.find();
{ "_id": ObjectId("5ca251a26304881c5ce84b8a"), "Score": NaN }
{ "_id": ObjectId("5ca2520e6304881c5ce84b8b"), "Score": 2 }
{ "_id": ObjectId("5ca252156304881c5ce84b8c"), "Score": Infinity }
{ "_id": ObjectId("5ca2521e6304881c5ce84b8d"), "Score": 0 }

Method 1: Using NaN Direct Comparison

Find documents where the Score field is NaN ?

db.nanDemo.find({ Score: NaN });
{ "_id": ObjectId("5ca251a26304881c5ce84b8a"), "Score": NaN }

Method 2: Using Mathematical Expression

Alternatively, you can use a mathematical expression that evaluates to NaN ?

db.nanDemo.find({ Score: 0/0 });
{ "_id": ObjectId("5ca251a26304881c5ce84b8a"), "Score": NaN }

Key Points

  • NaN (Not a Number) is a special IEEE 754 floating-point value in JavaScript and MongoDB.
  • Both NaN and 0/0 expressions work for querying NaN values.
  • NaN is the result of undefined or unrepresentable mathematical operations like 0/0.
  • Use NaN directly in queries for better readability and clarity.

Conclusion

MongoDB allows you to query for NaN values using either direct NaN comparison or mathematical expressions that evaluate to NaN. The direct approach with NaN is more readable and recommended for production code.

Updated on: 2026-03-15T00:43:11+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements