Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort the embedded objects in MongoDB

Suppose I have some objects in MongoDB:

{
 "_id":xxx, 
 "name":"mike", 
 "children": [
               {"name":"A", "age":3},
               {"name":"B", "age": 5}
             ]
}

If I want to get this "mike" with his children sorted by "age desc", what should I do?

I've looked at Mongoid(in rails), and morphia(in Java), not found the answer.

like image 997
Freewind Avatar asked Jul 17 '10 14:07

Freewind


1 Answers

I don't know of any way to do this. You'll probably want to sort the children in code (Ruby, Java) when they come back.

This is one of the typical limitations of Mongo, you don't really "sort" the sub-objects on the server. Instead you pull them from the DB and then sort the sub-objects as necessary.

like image 116
Gates VP Avatar answered Sep 23 '22 02:09

Gates VP