对嵌套的对象数组进行排序 [英] Sort nested array of objects
本文介绍了对嵌套的对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种对嵌套对象数组进行排序的方法.
I'm looking for a way to sort a nested array of objects.
这是一个例子:
{
answers : [
{ name : 'paul', state : 'RU' },
{ name : 'steve', state : 'US' },
{ name : 'mike', state : 'DE' },
...
]
}
假设现在我想找到 answers
数组的所有 name
,但我如何按升序对它们进行排序?
Suppose now I want to find all the name
, of the answers
array, but how can I sort them in ascending order?
推荐答案
我会按照你想要的顺序存储它.或者拉出来后排序,在客户端.
I would store it in the order you want it back out. Or sort it after you pull it out, on the client side.
如果这两个都不可能,您可以使用聚合框架:
If neither of those are possible, you can use the aggregation framework:
> db.test.insert({answers: [
... {name: 'paul', state: 'RU'},
... {name: 'steve', state: 'US'},
... {name: 'mike', state: 'DE'}]});
> db.test.insert({answers: [
... {name: 'paul', state: 'RU'},
... {name: 'steve', state: 'US'},
... {name: 'xavier', state: 'TX'}]});
db.test.aggregate([
{$unwind: "$answers"},
{$sort: {"answers.name":1}},
{$group: {_id:"$_id", answers: {$push:"$answers"}}}
]);
产生:
{
"result" : [
{
"_id" : ObjectId("5053b2477d820880c3469364"),
"answers" : [
{
"name" : "paul",
"state" : "RU"
},
{
"name" : "steve",
"state" : "US"
},
{
"name" : "xavier",
"state" : "TX"
}
]
},
{
"_id" : ObjectId("5053af9f7d820880c3469363"),
"answers" : [
{
"name" : "mike",
"state" : "DE"
},
{
"name" : "paul",
"state" : "RU"
},
{
"name" : "steve",
"state" : "US"
}
]
}
],
"ok" : 1
}
这篇关于对嵌套的对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文