How to select mongodb documents where field is a number?
Some examples of the content of this field: "2", "a", "Z", 3
to do a text search on all fields, you first must create a text index on all fields. as the mongodb documentation indicates, "To allow for text search on all fields with string content, use the wildcard specifier ($**) to index all fields that contain string content."
From MongoDB 4.4, you can use the $isNumber aggregation pipeline operator to check whether or not a value is a number. It accepts any valid expression, and returns true if the expression is a number, false if it's not.
ISODate() is a helper function that's built into to MongoDB and wraps the native JavaScript Date object. When you use the ISODate() constructor from the Mongo shell, it actually returns a JavaScript Date object.
You can use the $type operator to select based on the BSON type of the field, which should get you what you want.
So, for example, to find all strings:
db.collection.find( { field: { $type : 2 } } )
Or, to find all doubles (which is usually what numbers get stored as from the shell thanks to the default Javascript behavior), you would use:
db.collection.find( { field: { $type : 1 } } )
Since there are two types of integer (potentially) you would need to go with something like this:
db.collection.find({$or : [{"field" : { $type : 16 }}, {"field" : { $type : 18 }}]})
Finally then, to get all numbers, integer or double:
db.collection.find({$or : [{"field" : { $type : 1 }}, {"field" : { $type : 16 }}, {"field" : { $type : 18 }}]})
You can the type of a field bar
by using
typeof db.foo.findOne().bar
http://docs.mongodb.org/manual/core/shell-types/#check-types-in-shell
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With