我正嘗試使用計數將分組內的數據分組。在MongoDB中使用聚合框架分組並計數
{
"_id" : ObjectId("59899846b5f5670840040b0b"),
"client_id" : "merlin",
"scope" : "eee",
"user_id" : "u",
"user_directory" : "kmdkcn",
"createdAt" : ISODate("2017-08-08T10:53:58.816Z"),
"open_url" : null,
"__v" : 0
}
{
"_id" : ObjectId("59899849b5f5670840040b0c"),
"client_id" : "merlin",
"scope" : "eee",
"user_id" : "u",
"user_directory" : "kmdkcn",
"createdAt" : ISODate("2017-08-08T10:54:01.908Z"),
"open_url" : null,
"__v" : 0
}
{
"_id" : ObjectId("5989984db5f5670840040b0d"),
"client_id" : "merlin",
"scope" : "eee",
"user_id" : "y",
"user_directory" : "kmdkcn",
"createdAt" : ISODate("2017-08-08T10:54:05.280Z"),
"open_url" : null,
"__v" : 0
}
{
"_id" : ObjectId("5989adb2d699bd211caa07ad"),
"client_id" : "symphony",
"scope" : "eee",
"user_id" : "q",
"user_directory" : "kmdkcn",
"createdAt" : ISODate("2017-08-08T12:25:22.518Z"),
"open_url" : null,
"__v" : 0
}
{
"_id" : ObjectId("5989adb8d699bd211caa07ae"),
"client_id" : "symphony",
"scope" : "eee",
"user_id" : "w",
"user_directory" : "kmdkcn",
"createdAt" : ISODate("2017-08-08T12:25:28.954Z"),
"open_url" : null,
"__v" : 0
}
{
"_id" : ObjectId("5989adbcd699bd211caa07af"),
"client_id" : "symphony",
"scope" : "eee",
"user_id" : "q",
"user_directory" : "kmdkcn",
"createdAt" : ISODate("2017-08-08T12:25:32.753Z"),
"open_url" : null,
"__v" : 0
}
{
"_id" : ObjectId("5989adc0d699bd211caa07b0"),
"client_id" : "symphony",
"scope" : "eee",
"user_id" : "r",
"user_directory" : "kmdkcn",
"createdAt" : ISODate("2017-08-08T12:25:36.176Z"),
"open_url" : null,
"__v" : 0
}
我想要的是在client_id的基礎上進一步分組數據,並進一步根據user_id來獲取文檔的計數。
我曾經嘗試這樣做: -
Logger.aggregate([
{ "$group": {
"_id": {client: "$client_id"},
"count": { "$sum": 1 }
}}
])
我得到: - 客戶:梅林 數:3, 客戶端:交響樂, 數:4
但如何分組這個上user_id的基礎。
我想最後的結果將是: -
客戶端:梅林, 數:2, 客戶端:交響樂, 數:3
您的意思是*「每個用戶的每個客戶端」?* –