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

社会主义新天地 提交于 2019-11-29 10:11:43
db.collection.find( { field: NaN })

actually works although I couldn't find any documentation on it

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 issue because mongoexport (mongo 3.0.7) wrote NaN into the JSON files it created. This appears to have been addressed in 3.3.5.

So again using PyMongo and in a similar boat, you can replace NaN with Python's None, which mongoexport will convert 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'])}})
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!