MongoDB:在子文档中获取最大日期并保持文档结构

时间:2019-06-19 10:42:47

标签: mongodb aggregation-framework

我的文档结构如下:

_id: 5d090529397f79d2fefc57fb,    
result: 23232,
temperatures: { 
    temp_limits: { 
        min: 10,
        max: 31,            
    },
    temp_cities:
        [ 
            { 
                city: 'citie_1',
                city_temp: [ 
                    { temp: 17, date: 2018-12-18T10:35:07.000Z}, // I want this
                    { temp: 21, date: 2018-12-17T11:35:05.000Z},
                    { temp: 23, date: 2018-12-17T14:36:07.000Z},
                ],
                locked: false
            },
            { 
                city: 'citie_2',
                city_temp: [ 
                    { temp: 15, date: 2018-12-18T14:15:07.000Z}, // and this
                    { temp: 22, date: 2018-12-17T11:33:02.000Z}                        
                ],
                locked: false
            }
    ]
}

我想要每个date上的最大值temp和他的city_temp,但保持相同的结构。像这样:

_id: 5d090529397f79d2fefc57fb,    
result: 23232,
temperatures: { 
    temp_limits: { 
        min: 10,
        max: 31,            
    },
    temp_cities:
        [ 
            { 
                city: 'citie_1',
                city_temp: { temp: 17, date: 2018-12-18T10:35:07.000Z}                    
                locked: false
            },
            { 
                city: 'citie_2',
                city_temp: { temp: 15, date: 2018-12-18T14:15:07.000Z}
                locked: false
            }
    ]
}

我尝试了此操作,但结果分离或结构不同:

 {$unwind: '$temperatures.temp_cities'},
 {$unwind: '$temperatures.temp_cities.city_temp'},
 {$sort: { '$temperatures.temp_cities.city_temp.date': -1 } },
 {   
     $group: {
         _id: {
             _id: '$_id',
             bookie: "$temperatures.temp_cities.city"
         },                
         result: { $first: '$result' },             
         temperatures: {
             $first: "$temperatures.temp_cities.city_temp"
         }
     }
 }

1 个答案:

答案 0 :(得分:1)

您可以对嵌套的$map使用$filter运算符。最长日期可以使用$max运算符获取:

db.collection.aggregate([
    {
        $addFields: {
            "temperatures.temp_cities": {
                $map: {
                    input: "$temperatures.temp_cities",
                    as: "tc",
                    in: {
                        locked: "$$tc.locked",
                        city: "$$tc.city",
                        city_temp: {
                            $let: {
                                vars: { maxDate: { $max: "$$tc.city_temp.date" } },
                                in: {
                                    $arrayElemAt: [
                                        { $filter: { input: "$$tc.city_temp", cond: { $eq: [ "$$this.date", "$$maxDate" ] } } }, 0
                                    ]
                                }
                            }
                        }
                    }
                }
            }
        }
    }
])

Mongo Playground