我使用 MongoDb 已经有一段时间了,觉得它很棒。我有以下 Activity 对象。
[ Activity ]
"_id" : ObjectId("518a6c18e4b079d18de65b6e"),
"userUrl" : "http://news.bbc.co.uk",
"userAddress" : "1.2.3.4",
"requestTime" : ISODate("2013-05-08T15:15:35.780Z"),
"status" : "success"
注意,状态字段大约有 5 个不同的值,例如“错误”、“不可用”等
所以我现在处于对负载进行高级报告的阶段,但在分组功能方面存在问题。例如,如果我插入以下测试数据: -
db.activity.insert({"userUrl": "http://news.bbc.co.uk", "userAddress" : "1.2.3.4", "requestTime" : new Date('Jan 01, 2013'), "status": "success"})
db.activity.insert({"userUrl": "http://news.bbc.co.uk", "userAddress" : "1.2.3.4", "requestTime" : new Date('Jan 01, 2013'), "status": "success"})
db.activity.insert({"userUrl": "http://news.bbc.co.uk", "userAddress" : "1.2.3.4", "requestTime" : new Date('Jan 01, 2013'), "status": "error"})
db.activity.insert({"userUrl": "http://news.bbc.co.uk", "userAddress" : "1.2.3.4", "requestTime" : new Date('Jan 01, 2013'), "status": "unavailable"})
db.activity.insert({"userUrl": "http://news.bbc.co.uk", "userAddress" : "1.2.3.4", "requestTime" : new Date('Jan 02, 2013'), "status": "success"})
db.activity.insert({"userUrl": "http://news.bbc.co.uk", "userAddress" : "1.2.3.4", "requestTime" : new Date('Jan 02, 2013'), "status": "error"})
db.activity.insert({"userUrl": "http://news.bbc.co.uk", "userAddress" : "1.2.3.4", "requestTime" : new Date('Jan 02, 2013'), "status": "error"})
db.activity.insert({"userUrl": "http://news.bbc.co.uk", "userAddress" : "1.2.3.4", "requestTime" : new Date('Jan 02, 2013'), "status": "unavailable"})
db.activity.insert({"userUrl": "http://news.bbc.co.uk", "userAddress" : "1.2.3.4", "requestTime" : new Date('Jan 02, 2013'), "status": "unavailable"})
...我运行这个功能...
db.activity.group(
{
$keyf : function(doc) {
return { "date" : doc.requestTime.getDate() + "/" + doc.requestTime.getMonth() + "/" + doc.requestTime.getFullYear()};
},
initial: { count:0 },
reduce: function(obj, prev) { prev.count++; }
})
...我得到这个结果...
[
{
"date" : "1/0/2013",
"count" : 4
},
{
"date" : "2/0/2013",
"count" : 5
}
]
这非常适合仅在日期上进行分组。 我的问题是,我将如何按日期(按天)分组状态? 例如,得到这样的东西是理想的: -
[
{
"date" : "1/0/2013",
"success" : 2,
"error": 1,
"unavailable": 1
},
},
{
"date" : "2/0/2013",
"success" : 1,
"error": 2,
"unavailable": 2
}
]
... 或者 ...
[
{
"date" : "1/0/2013",
status: [
"success" : 2,
"error": 1,
"unavailable": 1
]
},
},
{
"date" : "2/0/2013",
status: [
"success" : 1,
"error": 2,
"unavailable": 2
]
}
]