How to say... match when field is a number... in mongodb?

Use the $type operator in your $match:

db.zips.aggregate([
    {$project : {city:{$substr:["$city",0,1]}}},
    {$sort : {city : 1}}, 
    {$match: {city: {$type: 16}}}      // city is a 32-bit integer
]);

There isn't a single type value for number so you need to know which type of number you have:

32-bit integer   16
64-bit integer   18
Double           1

Or use an $or operator to match all types of numbers:

db.zips.aggregate([
    {$project : {city:{$substr:["$city",0,1]}}},
    {$sort : {city : 1}}, 
    {$match: {$or: [{city: {$type: 1}}, {city: {$type: 16}}, {city: {$type: 18}}]}}
]);

Or even use $not to match all docs where city is not a string:

db.zips.aggregate([
    {$project : {city:{$substr:["$city",0,1]}}},
    {$sort : {city : 1}}, 
    {$match: {city: {$not: {$type: 2}}}}      // city is not a string
]);

UPDATED

To match all docs where city is a numeric string you can use a regular expression:

db.zips.aggregate([
    {$project : {city:{$substr:["$city",0,1]}}},
    {$sort : {city : 1}}, 
    {$match: {city: /^\d.*$/}}      // city is all digits
]);

Why not to use $regex?

db.zips.aggregate([
    {$project : {city:{$substr:["$city",0,1]}}},
    {$sort : {city : 1}}, 
    {$match: {city:{$regex:'[0-9]'}}}
])

Simply use:

db.zips.aggregate([
{$match: {
    'city': { $regex: '^[0-9].*'}
}}])

This work fine for me!

Tags:

Python

Mongodb