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

后端 未结 8 530
误落风尘
误落风尘 2021-02-04 07:41

So I have a field called \'city\' in my results...the results are corrupted, some times it\'s an actual name, sometimes it\'s a number. The following code displays all the recor

相关标签:
8条回答
  • 2021-02-04 08:35

    you can also try like the following, using regular expression without using $regex

    db.zips.aggregate([
    {$project : { city : { $substr : ["$city",0,1] } }}, 
    {$sort : {city : 1}}, 
    {$match: { city:/[0-9]/}}
    ])
    
    0 讨论(0)
  • 2021-02-04 08:38

    With the mongodb 4.4 (upcoming), You can use $isNumber pipeline operator to check whether the expression is integer or other BSON type.

    db.zips.find({ "$expr": { "$anyElementTrue": { "$isNumber": "$city" }}})
    

    $isNumber will return true or false corrsoponding to the expression and $anyElementTrue will return the $matched documents.

    0 讨论(0)
提交回复
热议问题