如何在MongoDB中对嵌入对象进行排序

时间:2022-09-11 16:10:59

Suppose I have some objects in MongoDB:

假设我在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?

如果我想把这个“迈克”和他的孩子按照“年龄desc”排序,我该怎么办?

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

我看过Mongoid(在rails中)和morphia(在Java中),没有找到答案。

1 个解决方案

#1


4  

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.

我不知道有什么方法可以做到这一点。您可能希望在回来时对代码(Ruby,Java)中的子进行排序。

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.

这是Mongo的典型限制之一,您实际上并没有“排序”服务器上的子对象。而是从数据库中提取它们,然后根据需要对子对象进行排序。

#1


4  

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.

我不知道有什么方法可以做到这一点。您可能希望在回来时对代码(Ruby,Java)中的子进行排序。

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.

这是Mongo的典型限制之一,您实际上并没有“排序”服务器上的子对象。而是从数据库中提取它们,然后根据需要对子对象进行排序。