gpt4 book ai didi

Mongodb 对内部数组进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 02:00:45 25 4
gpt4 key购买 nike

我已经找了一段时间了,似乎无法对内部数组进行排序并将其保留在我当前正在使用的文档中。

{
"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}});

有人认为他们可以为此提供帮助吗?

最佳答案

您可以通过$unwindupdates数组进行$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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com