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屋!
查看全文