2017-05-17 22 views
0

下面是我的模式..我需要得到my'file_id'(我將定義我的file_id)與不同的'user_email'計數..注意..不計數file_id與類似和不同的user_email我只需要計數我的file_id與不同的user_email.any幫助?如何查找和分組不同的值並在mongoDb中計數?

{ 
    "_id" : ObjectId("591bedc8c942a3514ed09b24"), 

    "file_id" : "58450c20b053dc426b935927", 
    "description" : "get your output ready", 
    "user_email" : "[email protected]", 
    "__v" : 0 
} 
{ 
    "_id" : ObjectId("591bedc8c942a3514ed09b25"), 

    "description" : "get your output ready", 
    "user_email" : "[email protected]", 
    "__v" : 0 
} 
{ 
    "_id" : ObjectId("591bedc8c942a3514ed09b26"), 

    "file_id" : "58450c20b053dc426b935927", 
    "description" : "get your output ready", 
    "user_email" : "[email protected]", 
    "__v" : 0 
} 
{ 
    "_id" : ObjectId("591bedc8c942a3514ed09b27"), 

    "file_id" : "58450c20b053dc426b935927", 
    "description" : "get your output ready", 
    "user_email" : "[email protected]", 
    "__v" : 0 
} 
{ 
    "_id" : ObjectId("591beea4a62559b4506549e0"), 

    "file_id" : "58450c20b053dc426b935927", 
    "description" : "get your output ready", 
    "user_email" : "[email protected]", 
    "__v" : 0 
} 



db.myschema.aggregate({$group:{"file_id":"58450c20b053dc426b935927","user_email" : "[email protected]",count: { $sum: 1 }} }) 
+0

你的問題不清楚 – Lekhnath

+0

我需要得到的文件id的數量,我用我的查詢與不同的用戶電子郵件定義..如果有10個記錄具有相同的file_id和相同的user_email我需要計數爲1而不是10. – Jagadeesh

回答

1

以下查詢應該給你的file_id獨特的計數和user_email

db.myschema.aggregate([ 

{ 
    $group: { 
    _id: {"file_id": "$file_id", "user_email": "$user_email"}, 
    count: {$sum: 1} 
    } 
}, 
{ 

    $project: { 
    _id: 0, 
    "user_email": "$_id.user_email", 
    "file_id": "$_id.file_id", 
    "count": 1 
    } 

} 

]); 

編輯 所以,如果你有興趣,特別file_id只有這樣,你可以簡單地過濾結果如下:

let fileId = '58450c20b053dc426b935927'; 

db.myschema.aggregate([ 
    { 
    $group: { 
     _id: { file_id: "$file_id", user_email: "$user_email" }, 
     count: { $sum: 1 } 
    } 
    }, 
    { 
    $match: { 
     "_id.file_id": fileId 
    } 
    }, 
    { 
    $project: { 
     _id: 0, 
     user_email: "$_id.user_email", 
     file_id: "$_id.file_id", 
     count: 1 
    } 
    } 
]); 
+0

雅這個查詢給出我計算每個不同記錄的唯一計數,例如: {「count」:12,「user_email」:「[email protected]」,「file_id」:「58450c20b053dc426b935927」} {「count」:1,「user_email 「:」[email protected]「,」file_id「:」5841509cbe1c099108a887f4「} {」count「:2,」user_email「:」[email protected]「,」file_id「:」5841509cbe1c099108a887f4「} {」count 「:1,」user_email「:」[email protected]「,」file_id「:」5841509cbe1c099108a887f4「} .... 但在此記錄中,我需要使用查詢搜索特定的file_id,我該怎麼做? – Jagadeesh

+0

這是我使用$匹配:)工作.... – Jagadeesh

+0

@Jagadeesh請參閱更新。是!您可以通過添加匹配聚合管道來過濾出所需的結果。 – Lekhnath

相關問題