我存储在我的收藏中的对象如下所示:
.footer {
bottom: 0;
margin: 0 auto !important;
text-align: center !important;
width: 100% !important;
height: 40px;
position: absolute; }
我希望使用单个查询检索PriceType等于4的[针对整个集合]的最小和最大价格值。
我找到了一种方法,但运行了两个不同的查询(基本上是相同的查询,但有不同的排序)
[{
"_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
}
]
}]
任何提示?
答案 0 :(得分:1)
这就是你要找的东西:
> db.Cars.aggregate([
{
$unwind:"$Prices"
},
{
$match:{"Prices.PriceType":4}
},
{
$group:
{_id:"$CarPlate",
max_price:{$max:"$Prices.Value"},
min_price:{$min:"$Prices.Value"}
}
},
{
$group:
{_id:null,
max_value:{$max:"$max_price"},
min_value:{$min:"$min_price"}
}
}
])
这将在整个集合中输出min和max的单个值。
答案 1 :(得分:0)
对于那些知道如何转换为c#这样的查询的人(再次感谢@ibininja),这里有c#代码:
this.carRepository
.Collection
.Aggregate()
.Match(priceTypeFilder)
.Unwind<Car, CarToPrice>(i => i.Prices)
.Match(x => x.Prices.PriceType == PriceTypeEnum.Catalog)
.Group(key => key.CarPlate ,
g => new
{
_id = g.Key,
MinPrice = g.Min(o => o.Prices.Value),
MaxPrice = g.Max(o => o.Prices.Value)
})
.Group(key => key._id,
g => new
{
_id = (string)null,
MinPrice = g.Min(o => o.MinPrice),
MaxPrice = g.Max(o => o.MaxPrice)
})
.SingleAsync();