【问题标题】:efficient way to aggregationresult聚合结果的有效方法
【发布时间】:2018-07-30 03:54:18
【问题描述】:

这是我的例子..

items: [
  {
   mart_code : 1,
   director: "James",
   category: "fruit",
   name: "apple",
   money: 5000
  },
  {
   mart_code: 1
   director: "James",
   category: "toy",
   name: "dragon",
   money: 15000
  },
  {
   mart_code: 2,
   director: "Sam",
   category: "fruit",
   name: "orange",
   money: 3500
  }
]

我想得到结果..

martList: [ {
  mart_code: 1,
  directorList:[
  {
   director: "James",
   money: 20000
  }
  ],
  categoryList: [
  {
   category: "fruit",
   money: 5000
  },
  {
   category: "toy",
   money: 15000
  }] 
},
{
  mart_code: 2,
  directorList:[
  {
   director: "Sam",
   money: 3500
  }
  ],
  categoryList: [
  {
   category: "fruit",
   money: 3500
  }]
}
]

我试图 $facet、$group、$unwind $project... 有没有有效的方法?

【问题讨论】:

  • 为什么要应用我的顶级示例自动感应......?对不起..

标签: mongodb aggregation-framework aggregation


【解决方案1】:

希望 $group$project 将是获得结果的有效方式

db.collection.aggregate([
{$group : {
    _id : {
        mart_code : '$mart_code',
        director : '$director',
        category : '$category'
        },
    money: {$sum : '$money'}
}},
{$group : {
    _id : '$_id.mart_code',
    directorList : {$push : {
        director: "$_id.director",
        money: '$money'
    }},
    categoryList : {$push : {
        category: "$_id.category",
        money: '$money'
    }}
}},
{$group : {
    _id : null,
     martList : {$push : {
        mart_code : '$_id',
        directorList : '$directorList',
        categoryList : '$categoryList'
    }}
}},
{$project : {
    _id : 0,
    martList : '$martList'
}}
])

【讨论】:

  • 谢谢,但这是不正确的......钱不相加​​..我想分组为金钱,并从mart_code分组..
  • 我修改了,你能检查一下
  • 谢谢.. 但是.. 这是正确的吗? mart_code 1 中的 directorList 是 {James, 5000}, {James, 15000} .. 我想在 mart_code 1 中获得 {James, 20000} ..
【解决方案2】:

我试过了。

db.collection.aggregate([
{$unwind : "$items" },
{$group : {
    _id : {
        mart_code : '$mart_code',
        director : '$director'
        },
    money: {$sum : '$money'},
    entry: {$push: {$$ROOT}}
}},
{$group : {
    _id : '$_id.mart_code',
    directorList : {$push : {
        director: "$_id.director",
        money: '$money'
    }},
    entry: {$push: "$entry"}
}},
{ $unwind : "$entry" },
{ $unwind : "$entry" },
{$group : {
    _id : {
        mart_code : '$_id',
        directorList : '$directorList',
        category : '$entry.category'
    },
    money: {$sum: "$entry.money"}
}},
{$group: {
    _id: {
        mart_code : '$_id',
        directorList : '$directorList',
    },
    categoryList:{ $push:{
      category: "$_id.category",
      money: "$money"
    }}
}}
{$project : {
    _id : 0,
    categoryList: "$categoryList",
    directorList: "$_id.directoryList"
}}
])

这不是一个有效的方法.....

【讨论】:

    猜你喜欢
    • 2013-10-12
    • 1970-01-01
    • 2019-07-09
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 2023-01-29
    相关资源
    最近更新 更多