MongoDB 检索具有最高值的数据
MongoDB retrieve data with highest value
我在 MongoDB 中有这个 collection:
[
{ _id: "...", "project": 244, "scanner": "powershell", "version": 2 },
{ _id: "...", "project": 244, "scanner": "powershell", "version": 3 },
{ _id: "...", "project": 244, "scanner": "powershell", "version": 4 },
{ _id: "...", "project": 244, "scanner": "powershell", "version": 4 }
]
我需要检索所有具有最高版本的文档,在这种情况下:
{ _id: "...", "project": 244, "scanner": "powershell", "version": 4 },
{ _id: "...", "project": 244, "scanner": "powershell", "version": 4 }
能找到最高的版本,按-1排序取第一个
如何将找到的结果应用于过滤器?
非常感谢
db.collection.aggregate([
{
"$group": { //Find max value
"_id": "null",
"maxV": {
"$max": "$version"
},
data: { // add all records to this array
$push: "$$ROOT"
}
}
},
{
$project: {
"output": {
$filter: {//Filter the matching record from the array in stage 1
input: "$data",
as: "d",
cond: {
$eq: [
"$$d.version",
"$maxV"
]
}
}
},
"_id": 0
}
}
])
如果你想摆脱关键 output
,你可以像 this play
那样多两个阶段
{
"$unwind": "$output"
},
{
"$replaceRoot": {
"newRoot": "$output"
}
}
我在 MongoDB 中有这个 collection:
[
{ _id: "...", "project": 244, "scanner": "powershell", "version": 2 },
{ _id: "...", "project": 244, "scanner": "powershell", "version": 3 },
{ _id: "...", "project": 244, "scanner": "powershell", "version": 4 },
{ _id: "...", "project": 244, "scanner": "powershell", "version": 4 }
]
我需要检索所有具有最高版本的文档,在这种情况下:
{ _id: "...", "project": 244, "scanner": "powershell", "version": 4 },
{ _id: "...", "project": 244, "scanner": "powershell", "version": 4 }
能找到最高的版本,按-1排序取第一个
如何将找到的结果应用于过滤器?
非常感谢
db.collection.aggregate([
{
"$group": { //Find max value
"_id": "null",
"maxV": {
"$max": "$version"
},
data: { // add all records to this array
$push: "$$ROOT"
}
}
},
{
$project: {
"output": {
$filter: {//Filter the matching record from the array in stage 1
input: "$data",
as: "d",
cond: {
$eq: [
"$$d.version",
"$maxV"
]
}
}
},
"_id": 0
}
}
])
如果你想摆脱关键 output
,你可以像 this play
{
"$unwind": "$output"
},
{
"$replaceRoot": {
"newRoot": "$output"
}
}