我有收藏品。
{
"cityIsoCode": "LED",
"flights": [{
"departureDate": "2019-01-03",
"fromIsoCode": "MOW",
"returnDate": "2019-01-09",
"totalPrice": 829
},{
"departureDate": "2019-01-03",
"fromIsoCode": "MOW",
"returnDate": "2019-01-04",
"totalPrice": 467
}, {
"departureDate": "2019-01-03",
"fromIsoCode": "MOW",
"returnDate": "2019-01-05",
"totalPrice": 838
}]
}
{
"cityIsoCode": "KZN",
"flights": [{
"departureDate": "2019-01-03",
"fromIsoCode": "MOW",
"returnDate": "2019-01-04",
"totalPrice": 518
}, {
"departureDate": "2019-01-03",
"fromIsoCode": "MOW",
"returnDate": "2019-01-03",
"totalPrice": 551
}, {
"departureDate": "2019-01-03",
"fromIsoCode": "MOW",
"returnDate": "2019-01-10",
"totalPrice": 765
}]
}
我需要按字段“ totalPrice”对嵌套集合“ flights”进行排序,并输出$ slice:“ flights”的[1,1],按文档字段“ cityIsoCode”分组。
我需要得到以下结果:
{
"cityIsoCode" : "LED",
"flights" : [
{
"departureDate": "2019-01-03",
"fromIsoCode": "MOW",
"returnDate": "2019-01-09",
"totalPrice": 829
}
]
}
{
"cityIsoCode" : "KZN",
"flights" : [
{
"departureDate": "2019-01-03",
"fromIsoCode": "MOW",
"returnDate": "2019-01-03",
"totalPrice": 551
}
]
}
我可以在mongo中进行操作,以及如何对其进行正确查询吗?
答案 0 :(得分:1)
您可以使用聚合管道执行此操作
db.t45.aggregate([
{$unwind : "$flights"},
{$sort : {"flights.totalPrice":1}},
{$group : {_id : {_id : "$_id", cityIsoCode : "$cityIsoCode"}, flights : {$push : "$flights"}}},
{$project : {_id : "$_id._id", cityIsoCode : "$_id.cityIsoCode", flights : {$slice : ["$flights", 1,1]}}}
]).pretty()
这是 mongo 3.4.10 版本
我相信在更高版本中,我们可以直接对数组元素进行排序,我们可以通过数组元素字段仅用 $unwind
来避免$sort
,$group
和$sort
和$project
必填字段