mysql - how to get projections in mongodb with group operator -
i have table columns column1 & column2 looks this
colum1 column2 1 2 3 b 2 b 4 b 6
if perform following sql in mysql
select column1, column2, count(*) table group column1;
result
column1 column2 count(*) 1 3 b 2 3
i want execute similar query on mongodb
i tried
query1: db.table.aggregate({$group: {_id:"$column1", count:{$sum:1}} }) query2: db.table.aggregate({$project: {column1:1, column2:1}}, {$group: {_id:"$column1", count:{$sum:1}} })
however result query2 same query1, seems can not populate fields other mentioned in $group column.
is there way populate other fields in mongodb along $group operator ?
i'm not sure read mysql query correctly, , don't understand why particularly useful, $first
seems accomplish same thing.
however, mentioned in $first
documentation, outcome depends on sorting should include sorting criterion.
data (column names shortened brevity)
> db.foo.insert({"c1" : "a", "c2" : 1}); > db.foo.insert({"c1" : "a", "c2" : 2}); > db.foo.insert({"c1" : "a", "c2" : 3}); > db.foo.insert({"c1" : "b", "c2" : 2}); > db.foo.insert({"c1" : "b", "c2" : 4}); > db.foo.insert({"c1" : "b", "c2" : 6});
aggregation query
> db.foo.aggregate({$group: {_id:"$c1", c2: { $first: "$c2" }, count:{$sum:1}} })
results
{ "result" : [ { "_id" : "b", "c2" : 2, "count" : 3 }, { "_id" : "a", "c2" : 1, "count" : 3 } ], "ok" : 1 }
Comments
Post a Comment