所以在我的results...the结果中有一个叫做‘城市’的字段,有时它是一个真实的名字,有时它是一个数字。下面的代码显示所有记录...
db.zips.aggregate([{$project : {city:{$substr:["$city",0,1]}}},{$sort : {city : 1}} ])我需要修改这一行,使其只显示名称为数字(2,3,4等)的城市的记录。....I认为我可以使用'$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"
    }我试图只显示与一个更大的“家庭作业”问题有关的带有数字string...this的记录,但直到我通过这一点,我才能进入实际的家庭作业问题。
发布于 2012-11-16 10:32:49
在$match中使用$type运算符
db.zips.aggregate([
    {$project : {city:{$substr:["$city",0,1]}}},
    {$sort : {city : 1}}, 
    {$match: {city: {$type: 16}}}      // city is a 32-bit integer
]);number没有单一的类型值,因此您需要知道您拥有哪种类型的number:
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
]);发布于 2014-03-09 01:02:06
为什么不使用$regex呢?
db.zips.aggregate([
    {$project : {city:{$substr:["$city",0,1]}}},
    {$sort : {city : 1}}, 
    {$match: {city:{$regex:'[0-9]'}}}
])发布于 2015-02-07 01:54:37
只需使用:
db.zips.aggregate([
{$match: {
    'city': { $regex: '^[0-9].*'}
}}])这对我来说很好!
https://stackoverflow.com/questions/13409386
复制相似问题