How to find all documents with NaN field in MongoDB?

I want to remove all geospatial fields that are NaN, so I can index my MongoDB correctly.

How to find all documents that have this?

db.collection.find( { field: {$not: { $type: 1 } } }) 

will not work because NaN is of type Number.

+6
source share
2 answers
 db.collection.find( { field: NaN }) 

actually works, although I could not find documentation on it

+15
source

Solution for PyMongo:

 # If you're alright with numpy as a dependency import numpy as np db.collection.find({ 'field': np.nan }) 

or

 db.collection.find({ 'field': float('nan') }) 

FYI: I ran into this problem because mongoexport (mongo 3.0.7) wrote NaN to the JSON files that it created. This seems to have been reviewed in 3.3.5 .

So, again using PyMongo and in a similar boat, you can replace NaN with Python None , which mongoexport converts to JSON valid null :

 import numpy as np for doc in list(db.collection.find({ 'field': np.nan })) update_one({'_id': ObjectId(doc['_id'])}, {'$set': {'field': (lambda x: None if np.isnan(x) else x)(doc['field'])}}) 
+2
source

Source: https://habr.com/ru/post/969943/


All Articles