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 following syntax

db.yourCollectionName.find( { yourFieldName: NaN })

Let us first create a collection with documents

> db.nanDemo.insertOne({"Score":0/0});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca251a26304881c5ce84b8a")
}
> db.nanDemo.insertOne({"Score":10/5});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca2520e6304881c5ce84b8b")
}
> db.nanDemo.insertOne({"Score":20/0});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca252156304881c5ce84b8c")
}
> db.nanDemo.insertOne({"Score":0/20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca2521e6304881c5ce84b8d")
}

Following is the query to display all documents from a collection with the help of find() method

> db.nanDemo.find().pretty();

This will produce the following output

{ "_id" : ObjectId("5ca251a26304881c5ce84b8a"), "Score" : NaN }
{ "_id" : ObjectId("5ca2520e6304881c5ce84b8b"), "Score" : 2 }
{ "_id" : ObjectId("5ca252156304881c5ce84b8c"), "Score" : Infinity }
{ "_id" : ObjectId("5ca2521e6304881c5ce84b8d"), "Score" : 0 }

Following is the query to find all documents with a field that is NAN in MongoDB

> db.nanDemo.find( { Score: 0/0 });

This will produce the following output

{ "_id" : ObjectId("5ca251a26304881c5ce84b8a"), "Score" : NaN }

The alternate query is as follows

> db.nanDemo.find( { Score: NaN })

This will produce the following output

{ "_id" : ObjectId("5ca251a26304881c5ce84b8a"), "Score" : NaN }

Updated on: 30-Jul-2019

758 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements