disruptive
disruptive

Reputation: 5946

Handling MongoDB fields which are strings and treating as numerics

I have a field stored in Mongo which is stored as a string, but most of the time it contains a number, but if that number doesn't exist it comprises 'N/A' string for example. I'm using PyMongo and looking for an effective way to perform a less-than and greater-than query, but obviously I do not want to do a comparison as string.

Here is what I have:

{"field": '5.6'} 
{"field": 'N/A'}

results = mongo.db.validated.find({"field": "$gt": float(minimum)}, "field": {"$lt": float(maximum)}})

So I would like to pick out values that like between minimum and maximum but ignore 'N/A'.

Upvotes: 3

Views: 110

Answers (1)

Sarath Nair
Sarath Nair

Reputation: 2868

You may add a type checking to query like this:

results = mongo.db.validated.find({"field": {"$type": 1, "$gt": float(minimum),"$lt": float(maximum)}})

$type:1 will return double datatypes.

Upvotes: 1

Related Questions