【发布时间】:2016-02-13 00:37:45
【问题描述】:
我的集合中存储了一个对象,如下所示:
[{
"_id" : ObjectId("56bcbe570793be2e5025567e"),
"CarPlate" : "AB123CD",
"Brand" : "BMW",
"Version" : "316d",
"Description" : "BMW 316d",
"Prices" : [
{
"PriceType" : NumberInt(0),
"VatType" : NumberInt(0),
"Currency" : "EUR",
"Value" : 20100.0
},
{
"PriceType" : NumberInt(3),
"VatType" : NumberInt(0),
"Currency" : "EUR",
"Value" : 23900.0
},
{
"PriceType" : NumberInt(4),
"VatType" : null,
"Currency" : "EUR",
"Value" : 30950.0
}
]
}, {
"_id" : ObjectId("56bcbe570793be2e5025567f”),
"CarPlate" : "AB123CE”,
"Brand" : "BMW",
"Version" : "318d",
"Description" : "BMW 318d",
"Prices" : [
{
"PriceType" : NumberInt(0),
"VatType" : NumberInt(0),
"Currency" : "EUR",
"Value" : 23900.0
},
{
"PriceType" : NumberInt(3),
"VatType" : NumberInt(0),
"Currency" : "EUR",
"Value" : 23900.0
},
{
"PriceType" : NumberInt(4),
"VatType" : null,
"Currency" : "EUR",
"Value" : 40250.0
}
]
}]
我想使用单个查询检索 [整个集合] 的最低和最高价格值,其中 PriceType 等于 4。
我找到了一种方法,但运行两个不同的查询(基本上相同的查询,但排序不同)
db.Cars.aggregate(
[
{
$unwind: '$Prices'
},
{
$match: {
'Prices.PriceType': 4
}
},
{
$group: {
_id: '$CarPlate',
valueMin: { $min: '$Prices.Value' },
valueMax: { $max: '$Prices.Value' }
}
},
{
$sort: {
valueMin: 1
}
},
{
$limit: 1
}
]
);
有什么提示吗?
【问题讨论】:
-
澄清您想为整个集合中的每个汽车/文档/对象找到最小值和最大值?或从整个集合中选择一分钟和一分钟
-
致全集
-
所以根据您的示例数据,您想要这样的结果吗?
{ min: 20100.0, max: 40250.0 } -
是的,没错。全系列最高价和最低价的一项记录
标签: mongodb mongodb-.net-driver