mongodb - 从分组文档中获取最后一个值和最小值
问题描述
我的文档模型如下所示:
{
"model": "ABC123",
"date": "2018-12-24T23:00:00.000+0000",
"price": "2000" ,
}
我想检索集合以获取文档数组:
[
{ "_id" : "ABC123", "newestDate" : ISODate("2018-12-26T23:00:00Z"), "newestPrice" : 2801.33, "lowestPriceAtAll": 1300 },
{ "_id" : "ABC124", "newestDate" : ISODate("2018-12-26T23:00:00Z"), "newestPrice" : 2801.33, "lowestPriceAtAll": 990}
]
其中_id
是model
字段,newestPrice
是最新文档的价格(按 分组model
),并且lowestPriceAtAll
是所有具有相同 的文档中的最低价格model
。
我询问了两个问题。首先是找到最低价格的文件:
offers.aggregate([
{ $sort: { "model": 1, "price": 1 }},
{
$group: {
_id: "$model",
lowestPrice: { "$first": "$price" },
lowestPriceDate: { "$first": "$date"},
}
}
])
二是查找最新文档:
offers.aggregate([
{ $sort: { "model": 1, "date": -1 }},
{
$group: {
_id: "$model",
newestDate: { "$first": "$date" },
newestPrice: { "$first": "$price"},
}
}
])
是否可以将这两个查询合并为一个?(最重要的是文档必须按model
字段分组)。
解决方案
您可以使用$facet
db.offers.aggregate([
{$facet :{
lowest: [
{ $sort: { "model": 1, "price": 1 }},
{
$group: {
_id: "$model",
lowestPrice: { "$first": "$price" },
lowestPriceDate: { "$first": "$date"},
}
}
],
newest: [
{ $sort: { "model": 1, "date": -1 }},
{
$group: {
_id: "$model",
newestDate: { "$first": "$date" },
newestPrice: { "$first": "$price"},
}
}
]
}}
])
推荐阅读
- python-3.x - 用于数据预处理的 Pickle
- javascript - JS:转发到 URL 中包含随机部分的站点
- javascript - 如何拆分具有 26 个不同字符串值的数组,在网页上显示为 1 个字符串?
- python - 你如何在python中找到前N个素数?
- objective-c - 如何安排本地通知
- javascript - 在 Typescript / Javascript 中使用 Number 或 number 是否重要?
- matrix - 围绕自定义枢轴点旋转
- environment-variables - codecept:在 PhpStorm + Babun 中找不到命令
- android - Android FileNotFound 可以读取并存在虚假媒体 whatsapp 文件
- ios - 如何从我的移动应用程序使用 Google Auth 登录 WordPress?