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
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
NaNand0/0expressions work for querying NaN values. - NaN is the result of undefined or unrepresentable mathematical operations like
0/0. - Use
NaNdirectly 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.
Advertisements
