1

I have collection structure as follows

{"pid" : 1 , id" : 2 ,"auther" : "xyz" , "book" : "pqr" , "time" : 1}

{"pid" : 1 ,"id" : 3 ,"auther" : "abc" , "book" : "stu" , "time" : 2}

{"pid" : 1 ,"id" : 2 ,"auther" : "def" , "book" : "vwx" , "time" : 3}

{"pid" : 1 ,"id" : 3 ,"auther" : "hij" , "book" : "yza" , "time" : 4}

{"pid" : 2 ,"id" : 3 ,"auther" : "hij" , "book" : "yza" , "time" : 4}

{"pid" : 2 ,"id" : 2 ,"auther" : "def" , "book" : "vwx" , "time" : 3}

I want to records sorted on time in descending order with same id records are group together.

means id containing 2 are group together.

currently may query is just like

db.coll.find({"pid" : 1}).sort({"time" : -1})

Is it possible in mongoDB to group record on field

Thanks.

Swapnil Sonawane
  • 1,445
  • 3
  • 22
  • 37

1 Answers1

1

I'm not sure I understand your problem (What did you mean "group"? - please write result you want).

Try this:

.find().sort({pid:1, time: -1})

First - sorting by pid ASC than sorting by time DESC

Mr.Wizard
  • 24,179
  • 5
  • 44
  • 125
Igor
  • 61
  • 5
  • i Want result in given format while giving following query db.coll.find({"pid" : 1}).sort({"time" : -1}) all the records same id will be group together rather than sort.means as follows for above collection structure {"pid" : 1 ,"id" : 3 ,..., "time" : 4}{"pid" : 1 ,"id" : 3 ,..., "time" : 2}{"pid" : 1 ,"id" : 2,..., "time" : 3}"pid" : 1 , id" : 2 ,..., "time" : 1} .find().sort({id:1, time: -1}) it works fine group records id but time sort high priority – Swapnil Sonawane Apr 25 '11 at 14:41