我有一个订单表:
{ "_id" : 1, "customer" : "1", price: 0 }
{ "_id" : 2, "customer" : "1", price: 100 }
{ "_id" : 3, "customer" : "1", price: 120 }
{ "_id" : 4, "customer" : "2", price: 150 }我想要得到每个客户的最小订单值。
$builder
->facet()
->field('customerOrders')
->pipeline(
$dm->createAggregationBuilder('Document\Order')->group()
->field('id')
->expression('$customer')
->field('lowestValue')
->min('$price')
->field('highestValue')
->max('$price')
);上面的代码可以工作。
{ "_id" : "1", "lowestValue" : 0, "highestValue" : 120 }
{ "_id" : "2", "lowestValue" : 150, "highestValue" : 150 }我想忽略价格为0或空的订单。
期望的结果:
{ "_id" : "1", "lowestValue" : 100, "highestValue" : 120 }
{ "_id" : "2", "lowestValue" : 150, "highestValue" : 150 }这个是可能的吗?
我可以使用$cond (聚合)吗?
{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }https://docs.mongodb.com/manual/reference/operator/aggregation/cond/
MongoDB 4.2
MongoDB ODM 2.0.3
发布于 2020-02-22 10:45:03
只需使用$gt开始您的管道: 0....that使用有效的文档启动数据集...
发布于 2020-02-22 17:18:59
根据Cahaba数据的建议,在分组之前过滤掉价格为0的订单。
db.orders.aggregate([
{
$match: { price: { $gt: 0 } }
},
{
$group: {
_id: "$customer",
lowestValue: { $min: "$price" },
highestValue: { $max: "$price" }
}
}
])发布于 2020-03-08 08:02:07
谢谢你的回复。我找到了另一个解决方案。
db.orders.aggregate([
{
$group: {
_id: "$customer",
lowestValue: {
$min: {
$cond: [{
$gt: ["$price", 0]
}, "$price", null]
}
}
}
}
]);理论聚合构建器
..。
->field('lowestValue')
->min($builder->expr()->cond($builder->expr()->gt('$price', 0), '$price', null))https://stackoverflow.com/questions/60346522
复制相似问题