Re: [mongodb-user] Sorting embedded array

39 views
Skip to first unread message

kristian kurniawan

unread,
Jan 21, 2013, 10:47:00 PM1/21/13
to mongod...@googlegroups.com
Hi Eva,

You can do sorting directly using Javascript array sort() function.

Best regards,

Kristian

2013/1/22 Evangelina Martinez <evange...@gmail.com>
Hi, 

Is it possible to order by a field of an embedded array? For instance, in the following example extracted from the Mongo documentation, is it possible to order the awards by year? 

I've tried: db.bios.find().sort({'awards.year': -1}) with no success. 
 {
      _id: 1,
      name: { first: 'John', last: 'Backus' },
      birth: new Date('Dec 03, 1924'),
      death: new Date('Mar 17, 2007'),
      contribs: [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ],
      awards: [
                {
                  award: 'W.W. McDowell Award',
                  year: 1967,
                  by: 'IEEE Computer Society'
                },
                {
                  award: 'National Medal of Science',
                  year: 1975,
                  by: 'National Science Foundation'
                },
                {
                  award: 'Turing Award',
                  year: 1977,
                  by: 'ACM'
                },
                {
                  award: 'Draper Prize',
                  year: 1993,
                  by: 'National Academy of Engineering'
                }
      ]
   }
Thanks in advance! Eva

--
You received this message because you are subscribed to the Google
Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com
To unsubscribe from this group, send email to
mongodb-user...@googlegroups.com
See also the IRC channel -- freenode.net#mongodb

Jorge Puente Sarrín

unread,
Jan 21, 2013, 9:32:18 PM1/21/13
to mongod...@googlegroups.com
Hello Evangelina,

For this, you can to use Aggregation Framework, using $unwind and $sort operator:

db.winners.aggregate([{$unwind: "$awards"}, {$sort: {"awards.year": -1}}])

With $unwind, Peels off the elements of an array individually.

The documentation has many usage examples:

Best regards.


2013/1/21 Evangelina Martinez <evange...@gmail.com>



--
Jorge Puente Sarrín.
Reply all
Reply to author
Forward
0 new messages