views:

64

answers:

1

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.

+1  A: 

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.

Gates VP
@Gates, thank you. After reading the docs of mongodb, I still not find a way. I think you are right, there is no way to do this :(
Freewind
It's a little annoying, but it should not be a big deal. Most languages (including Ruby) make it very easy to sort arrays. If you're only sorting small sets, then it won't matter if you do it on the server or the client.
Gates VP