【问题标题】:MongoDB aggregate with dual sumMongoDB 聚合与双卡
【发布时间】:2013-05-02 00:05:39
【问题描述】:

我收集了一些移动设备,我想计算每个制造商的设备并计算每个型号。到目前为止,我所能得到的是:

{ $group : { 
  _id : "$hw.man", 
  mantotal : { $sum : 1 },
  models : { $addToSet : "$hw.mod" } 
} }

result:
[{"_id":"LGE","mantotal":1,"models":["GT540"]},{"_id":"asus","mantotal":1,"models":["Nexus 7"]},{"_id":"samsung","mantotal":3,"models":["GT-I9300","GT-I9200"]}]

{ $group : { 
  _id : { man : "$hw.man", mod : "$hw.mod" }, 
  total : { $sum : 1 } }
}

result:
[{"_id":{"man":"LGE","mod":"GT540"},"total":1},{"_id":{"man":"asus","mod":"Nexus 7"},"total":1},{"_id":{"man":"samsung","mod":"GT-I9300"},"total":2},{"_id":{"man":"samsung","mod":"GT-I9200"},"total":1}]

我怎样才能达到这样的结果:

{"_id":"samsung","mantotal":3,"models":[{mod: "GT-I9300", modtotal: 2}, {mod: "GT-I9200", modtotal: 1}]}

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:

    假设您有一个代表手机的简单文档集合,其中列出了其制造商和型号,如下所示:

    > db.phones.find({},{_id:0})
    { "man" : "LG", "mod" : "GT540" }
    { "man" : "LG", "mod" : "AB123" }
    { "man" : "Apple", "mod" : "iPhone4" }
    { "man" : "Apple", "mod" : "iPhone5" }
    { "man" : "Apple", "mod" : "iPhone5" }
    { "man" : "LG", "mod" : "GT540" }
    { "man" : "LG", "mod" : "GT540" }
    { "man" : "Samsung", "mod" : "Galaxy" }
    

    以下是您如何多次分组以按制造商和型号获得总计和小计:

    > gg1 =
    {
     "$group" : {
        "_id" : {
            "ma" : "$man",
            "mo" : "$mod"
        },
        "subTotals" : {
            "$sum" : 1
        }
     }
    }
    > gg2 =
    {
     "$group" : {
        "_id" : "$_id.ma",
        "total" : {
            "$sum" : "$subTotals"
        },
        "models" : {
            "$push" : {
                "mod" : "$_id.mo",
                "sub" : "$subTotals"
            }
        }
     }
    }
    
    > db.phones.aggregate(gg1, gg2)
    {
    "result" : [
        {
            "_id" : "LG",
            "total" : 4,
            "models" : [
                {
                    "mod" : "AB123",
                    "sub" : 1
                },
                {
                    "mod" : "GT540",
                    "sub" : 3
                }
            ]
        },
        {
            "_id" : "Apple",
            "total" : 3,
            "models" : [
                {
                    "mod" : "iPhone5",
                    "sub" : 2
                },
                {
                    "mod" : "iPhone4",
                    "sub" : 1
                }
            ]
        },
        {
            "_id" : "Samsung",
            "total" : 1,
            "models" : [
                {
                    "mod" : "Galaxy",
                    "sub" : 1
                }
            ]
        }
    ],
    "ok" : 1
     }
    

    【讨论】:

      猜你喜欢
      • 2014-05-27
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 2020-09-20
      • 2021-01-15
      • 2015-12-03
      • 2014-03-06
      • 2016-07-02
      相关资源
      最近更新 更多