Mongodb group and sort

前端 未结 8 2180
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 15:31

How can I translate the following Sql query for Mongo?:

select a,b,sum(c) csum from coll wh         


        
8条回答
  •  不知归路
    2020-12-09 16:14

    Inspired by this example on mongo's website.

    GENERATE DUMMY DATA:

    > db.stack.insert({a:1,b:1,c:1,active:1})
    > db.stack.insert({a:1,b:1,c:2,active:0})
    > db.stack.insert({a:1,b:2,c:3,active:1})
    > db.stack.insert({a:1,b:2,c:2,active:0})
    > db.stack.insert({a:2,b:1,c:3,active:1})
    > db.stack.insert({a:2,b:1,c:10,active:1})
    > db.stack.insert({a:2,b:2,c:10,active:0})
    > db.stack.insert({a:2,b:2,c:5,active:1})
    

    MONGO QUERY:

    > db.stack.aggregate(
    ... {$match:{active:1}},
    ... {$group:{_id:{a:"$a", b:"$b"}, csum:{$sum:"$c"}}},
    ... {$sort:{"_id.a":1}})
    

    RESULT:

    {"result" : [
        {"_id" : {"a" : 1,"b" : 2},"csum" : 3},
        {"_id" : {"a" : 1,"b" : 1},"csum" : 1},
        {"_id" : {"a" : 2,"b" : 2},"csum" : 5},
        {"_id" : {"a" : 2,"b" : 1},"csum" : 13}
    ],"ok" : 1}
    

    (NOTE: I reformatted the shell result a bit so it is more readable)

提交回复
热议问题