2017-03-14 58 views
0

我有以下的數據庫MongoDB的SELECT COUNT

{"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() 

我怎樣才能提取的追隨者對匹配的行(詹姆斯,賈馬爾,簡)數量的總數是多少?

+0

不知道。在大數據集上嘗試了兩種方法,結果是不同的。 – Jerry

回答

0

試試這個:

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

你能否請[編輯]解釋爲什麼這段代碼回答這個問題?僅限代碼答案[阻止](http://meta.stackexchange.com/q/148272/274165),因爲他們沒有教導解決方案。 –

+0

按照您的要求,您要計算名稱以「ja」開頭的追隨者數量,因此查詢所說的記錄首先匹配用戶名以「ja」開頭的記錄,然後使用$ group記錄所有記錄的所有追隨者的總和。鏈接https://docs.mongodb.com/manual/reference/operator/aggregation/sum/,你會理解查詢 –