从分组文档中获取最后一个和最小值

Get last and minimal values from grouped documents

我的文档模型如下所示:

{
    "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 字段分组)。

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