Arrays MongoDB获取日期等于最大日期的结果
假设我有以下文件:Arrays MongoDB获取日期等于最大日期的结果,arrays,mongodb,mongodb-query,aggregation-framework,Arrays,Mongodb,Mongodb Query,Aggregation Framework,假设我有以下文件: [ { "callId": "17dac51e-125e-499e-9064-f20bd3b1a9d8", "caller": { "firstName": "Test", "lastName": "Testing", "phoneNumber": "1231231234" }, "routeHistory": [ { "assignedUserId": "cfa0ffe9-c
[
{
"callId": "17dac51e-125e-499e-9064-f20bd3b1a9d8",
"caller": {
"firstName": "Test",
"lastName": "Testing",
"phoneNumber": "1231231234"
},
"routeHistory": [
{
"assignedUserId": "cfa0ffe9-c77d-4eec-87d7-4430f7772e81",
"routeDate": "2020-01-01T06:00:00.000Z",
"status": "routed"
},
{
"assignedUserId": "cfa0ffe9-c77d-4eec-87d7-4430f7772e81",
"routeDate": "2020-01-03T06:00:00.000Z",
"status": "ended"
}
]
}
]
我想得到routeHistory.routeDate等于routeHistory中$max routeDate值的结果。我希望我的结果如下所示:
[
{
"callId": "17dac51e-125e-499e-9064-f20bd3b1a9d8",
"caller": {
"firstName": "Test",
"lastName": "Testing",
"phoneNumber": "1231231234"
},
"routeHistory": [
{
"assignedUserId": "cfa0ffe9-c77d-4eec-87d7-4430f7772e81",
"routeDate": "2020-01-03T06:00:00.000Z",
"status": "ended"
}
]
}
]
是否有一种干净的方法在单个聚合中执行此操作,以便可以应用额外的$match条件?您可以使用来定义临时变量为$max
日期,并与一起使用以获取第一个匹配元素:
db.collection.aggregate([
{
$addFields: {
routeHistory: {
$let: {
vars: {
maxDate: { $max: "$routeHistory.routeDate" }
},
in: {
$arrayElemAt: [
{ $filter: { input: "$routeHistory", cond: { $eq: [ "$$maxDate", "$$this.routeDate" ] } } },
0
]
}
}
}
}
}
])
编辑:
不带$let的版本
:
db.collection.aggregate([
{
$addFields: {
maxDate: {
$max: "$routeHistory.routeDate"
}
}
},
{
$addFields: {
routeHistory: {
$arrayElemAt: [
{
$filter: { input: "$routeHistory", cond: { $eq: [ "$$maxDate", "$$this.routeDate" ] } }
},
0
]
}
}
}
}
])
此解决方案可行,但是Amazon DocumentDB不支持$let。有没有办法避免偶然使用该运算符?@MichaelKitchell当然,您只需运行另一个
$addFields
即可将该变量添加到您的模型中:非常感谢!还有一个问题,如果routeHistory嵌套在另一个数组中,我的查询会是什么样子?例如见:@MichaelKitchell that;s mio比较复杂,因为在应用$max
之前必须展平数组数组。你可以看看这里:如果你做不到,请打开另一个问题我打开了另一个问题,这里: