how do I find all documents with a field that is N

2020-02-12 04:26发布

I want to delete all geospacial fields that are NaN so I can properly index my MongoDB.

How do I find all documents that have this though?

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

won't work since NaN is of type Number.

标签: mongodb nan
2条回答
走好不送
2楼-- · 2020-02-12 04:31

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'])}})
查看更多
我只想做你的唯一
3楼-- · 2020-02-12 04:42
db.collection.find( { field: NaN })

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

查看更多
登录 后发表回答