mongodb - MongoDB 查找与正则表达式匹配且价格最高的文档
问题描述
示例文档:
{"_id": <id>, "name" : "Bread_1", "version" : 1 }
{"_id": <id>, "name" : "Bread_2", "version" : 1 }
{"_id": <id>, "name" : "Bread_1", "version" : 2 }
{"_id": <id>, "name" : "Bread_2", "version" : 2 }
{"_id": <id>, "name" : "Bread_3", "version" : 1 }
所需输出:
{"_id": <id>, "name" : "Bread_1", "version" : 2 }
{"_id": <id>, "name" : "Bread_2", "version" : 2 }
{"_id": <id>, "name" : "Bread_3", "version" : 1 }
它是按名称和最大版本分组的。我试过这个查询:
db.products.aggregate({$group: {_id: {name: '$name'}, version: {$max: '$version'}}});
实际输出:
{"_id": {"name" : "Bread_1"}, "version" : 2 }
{"_id": {"name" : "Bread_2"}, "version" : 2 }
{"_id": {"name" : "Bread_3"}, "version" : 1 }
虽然我也需要文档的 ID。在这种情况下我错过了什么?谢谢
解决方案
没有直接的方法可以得到它,所以你可以试试下面的查询:
db.products.aggregate([
/** Group on 'name' & get max of 'version' & push all docs to 'docs' array field */
{
$group: {
_id: "$name",
version: { $max: "$version" },
docs: { $push: "$$ROOT" }
}
},
/** Transform fields in required format, Iterate over docs array & get '_id' of doc where version do match */
{
$project: {
name: "$_id",
version: 1,
_id: {
$let: {
vars: {
id: {
$arrayElemAt: [ // As filter returns an array get first doc, There can only be one doc
{
$filter: {
input: "$docs",
cond: { $eq: ["$$this.version", "$version"] } // Check max version == current object's version
}
},
0
]
}
},
in: "$$id._id"
}
}
}
}
]);
测试: MongoDB-游乐场
推荐阅读
- c# - 有没有办法将凭据传递给 WebBrowser Control?
- r - 合并函数产生随机 NA
- selenium-webdriver - 无法在 Chrome 浏览器中使用 Night Watch 和 Selenium 运行单一测试
- javascript - 如何在 DOM 上修改帖子的 Order 属性
- time - 如何将 UNIX 时间戳转换为 Kotlin 中的 UInt8 数组?
- rust - 如何在结构中存储对象及其引用
- javascript - 如何在验证时显示弹出窗口?
- python - 代码遇到意外的无限while循环?
- button - HighCharts Cloud 切换数据表
- vmware - 在 vmware vm 上启用 cpu 性能计数器