Introduction to MongoDB $isNumber Operator

$isNumber is a logical operator in MongoDB used to determine whether a field is of a numeric type.

Syntax

The syntax of the $isNumber operator is as follows:

{ $isNumber: <expression> }

Here, <expression> is the expression to be evaluated for numeric type, and it can be any valid expression.

Use Cases

In MongoDB, sometimes it’s necessary to filter and classify data for aggregation analysis. The $isNumber operator can be used to filter out all documents in a collection with specified fields of numeric type to meet the needs of data classification and aggregation analysis.

Example

Suppose there is a collection named students that contains the following documents:

{ "_id": 1, "name": "Alice", "age": 20 }
{ "_id": 2, "name": "Bob", "age": "30" }
{ "_id": 3, "name": "Charlie", "age": 25 }

Now, we want to find all documents in the collection where the age field is of numeric type. We can use the following query statement:

db.students.find({ $isNumber: "$age" })

After executing the above query statement, the results will be as follows:

{ "_id": 1, "name": "Alice", "age": 20 }
{ "_id": 3, "name": "Charlie", "age": 25 }

As can be seen, the query results only contain documents where the age field is of numeric type.

Conclusion

The $isNumber operator is a commonly used logical operator in MongoDB that can be used to determine whether a field is of a numeric type. It can play an important role in data classification and aggregation analysis.