-1

i want to mongodb query this sql query's:

select x,y,message,foo from messege where x=1 and y=1 group by x,y order by _id DESC

but with :

MongoCollection::group

can anyone help me?

Community
  • 1
  • 1
Musher
  • 85
  • 1
  • 2
  • 7
  • http://stackoverflow.com/questions/3214406/how-to-group-by-with-mongodb?rq=1 – int Nov 24 '12 at 15:23
  • I'm confused by the "order by" part of the query - you will only have a single result since you are grouping by a single value (x and y both 1) - are you sure this is the SQL you really want? There is no aggregation here. – Asya Kamsky Nov 24 '12 at 15:26
  • @AsyaKamsky yes, i test it on mysql – Musher Nov 24 '12 at 16:02
  • Could you post the result please? I don't see how this can possibly return more than one row. – Asya Kamsky Nov 24 '12 at 21:39

1 Answers1

1

For this

select a,b,sum(c) csum from coll where active=1 group by a,b

The respective is

db.coll.group(
           {key: { a:true, b:true },
            cond: { active:1 },
            reduce: function(obj,prev) { prev.csum += obj.c; },
            initial: { csum: 0 }
            });

You cannot sort the results you get from group, you can use sort for find like this for desc -1 , 1 for asc : .sort({"_id":-1}) desc

check this http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Group

cezar
  • 94
  • 4
  • How can you add sort by _id when that's not part of your output? – Asya Kamsky Nov 24 '12 at 15:28
  • where to add '.sort()' . group return object and array, not cursor. i want to get last records that suited where. not sort desc – Musher Nov 24 '12 at 15:56
  • Well you cannot sort the results you get with group, you can do it client side or use mapReduce http://www.mongodb.org/display/DOCS/MapReduce – cezar Nov 24 '12 at 16:07
  • you absolutely CAN sort results you get back with group - you just can't sort them by key that's not there, same as SQL – Asya Kamsky Nov 26 '12 at 14:36