Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo. how to check if field is a number

How to select mongodb documents where field is a number?

Some examples of the content of this field: "2", "a", "Z", 3

like image 715
Andrei Avatar asked May 03 '13 11:05

Andrei


People also ask

How can check field value in MongoDB?

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."

Is not a number MongoDB?

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.

What is ISODate in MongoDB?

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.


2 Answers

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 }}]})
like image 83
Adam Comerford Avatar answered Oct 13 '22 06:10

Adam Comerford


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

like image 17
ebr Avatar answered Oct 13 '22 06:10

ebr