【问题标题】:SQL to Mongo AggregationSQL 到 Mongo 聚合
【发布时间】:2018-10-25 10:17:27
【问题描述】:

您好,我想将我的 sql 查询更改为 mongo 聚合。

select c.year, c.minor_category, count(c.minor_category) from Crime as c 
group by c.year, c.minor_category having c.minor_category = (
    Select cc.minor_category from Crime as cc where cc.year=c.year group by
    cc.minor_category order by count(*) desc, cc.minor_category limit 1)

我试着做这样的事情:

 db.crimes.aggregate({ 
$group: {
    "_id": {
        year: "$year", 
        minor_category :"$minor_category", 
        count: {$sum: "$minor_category"} 
     } 
   },
}, 
{
    $match : {
           minor_category: ?
    }
})

但我卡在 $match 中,这相当于拥有,但我不知道如何像在我的 sql 查询中那样在 mongo 中进行子查询。

谁能帮帮我?

【问题讨论】:

  • 从 SQL 查询看来,给定年份有很多 minor_category,而子查询正在获取特定年份中计数最高的 minor_category。所以最后,输出是每年获得最高计数的minor_category。请确认我的理解是否正确?
  • @mintekhab 正是它!
  • @MateuszZ 回答如下。查询有点大,适合评论部分。

标签: mongodb mongodb-query aggregation-framework aggregate


【解决方案1】:

好的,根据上面的确认,下面的查询应该可以工作了。

db.crime.aggregate
([
  {"$group":{"_id":{"year":"$year","minor":"$minor"},"count":{"$sum":1}}},
  {"$project":{"year":"$_id.year","count":"$count","minor":"$_id.minor","document":"$$ROOT"}},
  {"$sort":{"year":1,"count":-1}},
  {"$group":{"_id":{"year":"$year"},"orig":{"$first":"$document"}}},
  {"$project":{"_id":0,"year":"$orig._id.year","minor":"$orig._id.minor","count":"$orig.count"}}
)]

【讨论】:

    【解决方案2】:

    这将转换为以下 MongoDB 查询:

    db.crime.aggregate({
        $group: { // group by year and minor_catetory
            _id: {
                "year": "$year",
                "minor_category": "$minor_category"
            },
            "count": { $sum: 1 }, // count all documents per group,
        }
    }, {
        $sort: {
            "count": -1, // sort descending by count
            "minor_category": 1 // and ascending by minor_category
        }
    }, {
        $group: { // now we get the highst element per year
            _id: "$_id.year", // so group by year
            "minor_category": { $first: "$_id.minor_category" }, // and get the first (we've sorted the data) value
            "count": { $first: "$count" } // same here
        }
    }, {
        $project: { // remove the _id field and add the others in the right order (if needed)
            "_id": 0,
            "year": "$_id",
            "minor_category": "$minor_category",
            "count": "$count"
        }
    })
    

    【讨论】:

    • 上面提到的 SQL 查询使用 MSSQL 支持的 TOP 。其他 RDBMS 支持 Limit (postgresql)。此外,对于 mongo 查询,排序应该在 year 和 count 上。单独计数不会给出所需的结果。限制 1 将只给出一条记录,而不是每年给出一条记录。
    • 谢谢,我来自 SQL 背景,这就是为什么我最初误解了查询(这也是单条记录的来源)。不过,我不同意排序声明。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2018-07-15
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多