Mongodb 排序内部数组 [英] Mongodb sort inner array
本文介绍了Mongodb 排序内部数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在寻找一段时间,但似乎无法对内部数组进行排序并将其保存在我目前正在使用的文档中.
I've been looking for a while now and can't seem to sort an inner array and keep that in the doc that I'm currently working with.
{
"service": {
"apps": {
"updates": [
{
"n" : 1
"date": ISODate("2012-03-10T16:15:00Z")
},
{
"n" : 2
"date": ISODate("2012-01-10T16:15:00Z")
},
{
"n" : 5
"date": ISODate("2012-07-10T16:15:00Z")
}
]
}
}
}
所以我想保留要作为服务返回的项目,但对我的更新数组进行排序.到目前为止,我拥有的外壳:
So I want to keep the item to be returned as the service, but have my updates array sorted. So far with the shell I have:
db.servers.aggregate(
{$unwind:'$service'},
{$project:{'service.apps':1}},
{$unwind:'$service.apps'},
{$project: {'service.apps.updates':1}},
{$sort:{'service.apps.updates.date':1}});
有人认为他们可以提供帮助吗?
Anyone think they can help on this?
推荐答案
您可以通过 $unwind
对 updates
数组进行排序,并按 date
,然后 $group
使用排序顺序将它们在 _id
上重新组合在一起.
You can do this by $unwind
ing the updates
array, sorting the resulting docs by date
, and then $group
ing them back together on _id
using the sorted order.
db.servers.aggregate(
{$unwind: '$service.apps.updates'},
{$sort: {'service.apps.updates.date': 1}},
{$group: {_id: '$_id', 'updates': {$push: '$service.apps.updates'}}},
{$project: {'service.apps.updates': '$updates'}})
这篇关于Mongodb 排序内部数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文