我已经找了一段时间了,似乎无法对内部数组进行排序并将其保留在我当前正在使用的文档中。
{
"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")
}
]
}
}
}
所以我想保留要作为服务返回的项目,但对我的更新数组进行排序。到目前为止,我拥有的外壳:
db.servers.aggregate(
{$unwind:'$service'},
{$project:{'service.apps':1}},
{$unwind:'$service.apps'},
{$project: {'service.apps.updates':1}},
{$sort:{'service.apps.updates.date':1}});
有人认为他们可以为此提供帮助吗?
最佳答案
您可以通过$unwind
对updates
数组进行$unwind
操作,按日期
对生成的文档进行排序,然后使用排序顺序$group
将它们重新组合到_id
上来实现此目的。
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 对内部数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46055487/