MongoDB filter out entries that have field value impossible to be parsed to integer

Viewed 184

I am new to MongoDB. I have a data set that consists of field called 'page' which value is given as a string, e.g. '153'. I want to filter out all the entries which page field value that cannot be parsed to integer, so for instance value like 'page 25'. How do you go about doing this? I know if I use $toInt this will change strings to integers, but when it cannot it will throw an error. I am using Python btw.

db.collection.find({'page':{'$toInt':'$page'}}) 

This converts to integer all the parseable strings but throws out error when it cannot.

1 Answers

What about this one:

db.collection.find({
  $expr: {
    $ne: [
      "int",
      {
        $type: {
          $convert: {
            input: "$page",
            to: "int",
            onError: null,
            onNull: null
          }
        }
      }
    ]
  }
})

Mechanism:

  • $convert takes $page to integer or null
  • $type takes retrieves either "int" or "null"
  • if type is null (or not converted to number), then it's retrieved.

Basically, Anything that can't be converted goes to null.


Atlas aggregation translates to this, and could also be good:

pipeline = [
    {
        '$match': {
            '$expr': {
                '$ne': [
                    'int', {
                        '$type': {
                            '$convert': {
                                'input': '$page', 
                                'to': 'int', 
                                'onError': None, 
                                'onNull': None
                            }
                        }
                    }
                ]
            }
        }
    }
]
db.collection.aggregate(pipeline)

playground

Related