怎么说...匹配当字段是一个数字...在mongodb?

the*_*nso 13 python mongodb

所以我的结果中有一个名为"城市"的字段...结果已损坏,有时它是实际名称,有时它是一个数字.以下代码显示所有记录......

db.zips.aggregate([{$project : {city:{$substr:["$city",0,1]}}},{$sort : {city : 1}} ])
Run Code Online (Sandbox Code Playgroud)

我需要修改这一行,只显示一个城市名称是数字(2,3,4等)的记录....我想我可以使用'$ match',但是如何?

db.zips.aggregate([{$project : {city:{$substr:["$city",0,1]}}},{$sort : {city : 1}}, {$match:{???what_to_say_here???} ]) 
Run Code Online (Sandbox Code Playgroud)

怎么说'当城市是一个数字时匹配'?

我看起来像这样......

    {
        "city" : "A",
        "_id" : "04465"
    },
    {
        "city" : "1",
        "_id" : "02821"
    },
    {
        "city" : "0",
        "_id" : "04689"
    }
Run Code Online (Sandbox Code Playgroud)

我试图只显示带有数字字符串的记录...这与更大的"家庭作业"问题有关但我甚至无法得到实际的作业问题,直到我超越这一点.

Joh*_*yHK 30

$type在您的使用中使用运算符$match:

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

数字没有单一类型值,因此您需要知道您拥有的数字类型:

32-bit integer   16
64-bit integer   18
Double           1
Run Code Online (Sandbox Code Playgroud)

或使用$or运算符匹配所有类型的数字:

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

甚至用于$not匹配所有city不是字符串的文档:

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

更新

要匹配所有文档,其中city是数字字符串,您可以使用正则表达式:

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


小智 19

为什么不使用$ regex?

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