如何通过指定函数进行分组以获取密钥? [英] How to group by specifying a function to fetch a key?
问题描述
假设我向 mongo db 报告了 Web 应用程序错误.要获取它们(按 URL 分组),我使用以下查询:
db.errors.group({条件: {日期:{$gt:new Date(2013,0,3,6,0,0),$lt:new 日期(2013,0,3,8,0,0)}},钥匙: {网址:1},最初的: {总和:0},减少:功能(对象,上一个){prev.csum++;}})
如果我想通过网站网址(而不是页面网址)计算错误,我该怎么办?我的意思是,http://www.mysite.com/page1 和 http://www.mysite.com/page2 将被计入同一个存储桶中.理想情况下,它应该是查询的 key
部分中的一个函数......
扩展 JohnnyHK 的回答:
db.errors.group({条件: {日期:{$gt:new Date(2013,0,3,6,0,0),$lt:new 日期(2013,0,3,8,0,0)}},keyf:函数(文档){返回 { 站点:doc.url.match(/.*:\/\/[^\/]+/i)[0]};},最初的: {总和:0},减少:功能(对象,上一个){prev.csum++;}})
返回:
<预><代码>[{"site" : "http://www.mysite.com",总和":3},{"site": "http://www.example.com",总和":1}]对于大型数据集,它不会很快.如果您控制生成错误的代码,则添加可以分组的 domain
字段可能会更容易.
Suppose I have web application errors reported to mongo db. To fetch them (grouped by URLs) I use the following query:
db.errors.group({
cond: {
date:{
$gt:new Date(2013,0,3, 6, 0, 0),
$lt:new Date(2013,0,3, 8, 0, 0)
}
},
key: {
url: 1
},
initial: {
csum: 0
},
reduce:
function(obj, prev) {
prev.csum++;
}
})
What should I do if I would like to count the errors by a site url (as opposed to a page url)? I mean, that http://www.mysite.com/page1 and http://www.mysite.com/page2 will be counted in the same bucket. Ideally, it would be a function in the key
section of the query somehow...
To extend JohnnyHK's answer:
db.errors.group({
cond: {
date:{
$gt:new Date(2013,0,3, 6, 0, 0),
$lt:new Date(2013,0,3, 8, 0, 0)
}
},
keyf: function(doc)
{
return { site: doc.url.match(/.*:\/\/[^\/]+/i)[0]};
},
initial: {
csum: 0
},
reduce:
function(obj, prev) {
prev.csum++;
}
})
Returns:
[
{
"site" : "http://www.mysite.com",
"csum" : 3
},
{
"site" : "http://www.example.com",
"csum" : 1
}
]
With a large dataset it's not going to be fast though. If you control the code that generates the errors it might be easier to add a domain
field you could group on.
这篇关于如何通过指定函数进行分组以获取密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!