首页 > 解决方案 > 从分组文档中获取最后一个值和最小值

问题描述

我的文档模型如下所示:

{
    "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}
]

其中_idmodel字段,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字段分组)。

标签: mongodbnosqlaggregation

解决方案


您可以使用$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"},
                }
            }
        ]
    }}
])

推荐阅读