MongoDB选择计数

时间:2017-03-14 10:41:17

标签: mongodb

我有以下数据库

{"userName":"John Smith", "followers":8075,"body":"my text 1","confirmed":"no"}
{"userName":"james Bond", "followers":819, "body":"my text 2", "confirmed":"yes"}
{"userName":"Julia Roberts","followers":3882,"body":"my text 3","confirmed":"yes"}
{"userName":"Jamal David","followers":6531, "body":"my text 4","confirmed":"yes"}
{"userName":"jane fonda","followers":3941, "body":"my text 5","confirmed":"no"}

我需要计算名称以Ja开头的关注者数量(不区分大小写

我试图这样做,但这个选择为我提供了所有匹配的行。

db.collections.find( { $and:[{followers: { $gte: 0 } }, {"userName" : {$regex :/^Ja/i}}  ]})

这只会给出匹配行的总数

db.collections.find( { $and:[{followers: { $gte: 0 } }, {"userName" : {$regex :/^Ja/i}}  ]}).count()

如何为匹配的行(james,Jamal,jane)提取多个粉丝?

1 个答案:

答案 0 :(得分:0)

试试这个:

db.collections.aggregate([{
$match:{"userName":{$regex :/^Ja/i}}
},
{$group:{
_id:null,
followers: {$sum: "$followers"}
}}])