怎么说。。。当字段是数字时匹配。。。在mongodb中?

2024-05-28 23:50:46 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我的结果中有一个名为“city”的字段……结果被破坏了,有时是一个实际名称,有时是一个数字。以下代码显示所有记录。。。

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

我需要修改这一行,以便只显示城市名为数字(2、3、4等)的记录…我想我可以使用“$match”,但如何使用?

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

如何说“城市是数字时匹配”?

我得到的输出看起来像这样。。。

    {
        "city" : "A",
        "_id" : "04465"
    },
    {
        "city" : "1",
        "_id" : "02821"
    },
    {
        "city" : "0",
        "_id" : "04689"
    }

我试图只显示带有数字字符串的记录…这与一个更大的“家庭作业”问题有关,但我甚至无法进入实际的家庭作业问题,直到我通过这一点。


Tags: 代码project名称idcitydbmatch记录
3条回答

为什么不使用$regex?

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

$match中使用^{}运算符:

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

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

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

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

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

或者甚至使用$not来匹配city不是字符串的所有文档:

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

已更新

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

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

简单使用:

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

这工作对我来说很好!

相关问题 更多 >

    热门问题