下面是我的示例文档:我想使用聚合查询获取最大版本的错误。
{
"_id": {
"objectIdentifier": {
"identifier": {
"Empid": "715e66c7-92ff-4619-9324-2c708489fe27"
},
"objectName": "EmployeeInfoValidationValue"
},
"Empid": "715e66c7-92ff-4619-9324-2c708489fe27"
},
"Versions": [
{
"errors": [
{
"level": "ERROR",
"message": "Employee Name missing",
"timestamp": NumberLong(1531509214154)
}
],
"resultSetId": "6314a9b1-1bb0-4ba7-8128-9db39085339c",
"scope": "INPUT_QUALITY",
"validationLevelSeverity": "ERROR",
"validationResultsIdentifier": {
"identifier": {
"objectIdentifier": {
"identifier": {
"Empid": "715e66c7-92ff-4619-9324-2c708489fe27"
},
"objectName": "EmployeeInfoValidationValue"
},
"Empid": "715e66c7-92ff-4619-9324-2c708489fe27"
},
"objectName": "ValidationResult"
},
"version": NumberLong(10039)
},
{
"errors": [
{
"level": "ERROR",
"message": "Employee Name length is not within specified range",
"timestamp": NumberLong(1531123789457)
}
],
"resultSetId": "8743100a-1464-46af-b4d6-6636c47c8f36",
"scope": "INPUT_QUALITY",
"validationLevelSeverity": null,
"validationResultsIdentifier": {
"identifier": {
"objectIdentifier": {
"identifier": {
"Empid": "715e66c7-92ff-4619-9324-2c708489fe27"
},
"objectName": "EmployeeInfoValidationValue"
},
"Empid": "715e66c7-92ff-4619-9324-2c708489fe27"
},
"objectName": "ValidationResult"
},
"version": NumberLong(10097)
}
]
}
我编写了聚合查询,它显示了具有最高版本的所有记录-例如,显示最高版本:NumberLong(10097)
。在这种情况下,我不确定如何将Versions.errors
显示为“雇员姓名长度不在指定范围内”。
这是我写的查询:
db.ValidationResults.aggregate(
[
{
$match: {
"_id.Empid" : "715e66c7-92ff-4619-9324-2c708489fe27",
"Versions.scope" : "INPUT_QUALITY"
}
},
{
$project:
{
versionMax: {$max: "$Versions.version"}
}
}
]
)
我尝试$addFields
来显示错误,但是它只返回null(不起作用)。 TIA
答案 0 :(得分:0)
您可以在下一个流水线阶段将versionMax
与$filter一起使用,以获取version
等于$max
值的单项数组。然后,您可以使用$unwind将单元素数组转换为对象:
db.ValidationResults.aggregate([
{
$project: {
Versions: 1,
MaxVersion: { $max: "$Versions.version" }
}
},
{
$project: {
Versions: {
$filter: {
input: "$Versions",
as: "x",
cond: { $eq: [ "$$x.version", "$MaxVersion" ] }
}
}
}
},
{
$unwind: "$Versions"
}
])