在MongoDB中按多个字段分组 [英] Grouping by multiple fields in MongoDB

查看:66
本文介绍了在MongoDB中按多个字段分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的文档结构:

{
    "ip_address" : "192.168.133.12",
    "timestamp" : "2014-08-28T06:41:24",
    "response" : 400,
    "uri" : {
        "term" : "Something",
        "page" : "10",
        "category" : "category 10"
    }
}

如果我想对单个字段响应"进行分组,请按照以下步骤操作:

If I want to do groupby on a single field 'response' I will do it as follows:

db.collName.aggregate({ $group : {_id : "$response", total : { $sum : 1 }} });

如何将2个字段分组或说3个字段?是否可以对多个字段进行分组,以使它们形成具有相似值的汇总?

How do I group by 2 or say 3 fields? Is it possible to groupby multiple fields, so that they form a aggregate with similar values?

我的意思是这样的:

{
    "result" : [ 
        {
            "_id" : "responseValue" + "ip_addressValue",
            "totaling" : 3
        }
    ],
    "ok" : 1
} 

推荐答案

是的,您可以执行以下操作

Yes possible, you could do something like below

db.collName.aggregate({ $group : 
 {
   "_id" : {"response":"$response", "ip_address":"$ip_address"}, 
   total : { $sum : 1 }
 } 
});

这篇关于在MongoDB中按多个字段分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆