1

I have an Orders table:

{ "_id" : 1, "customer" : "1", price: 0 }
{ "_id" : 2, "customer" : "1", price: 100 }
{ "_id" : 3, "customer" : "1", price: 120 }
{ "_id" : 4, "customer" : "2", price: 150 }

I want to get the minimum order value for each customer.

$builder
    ->facet()
        ->field('customerOrders')
        ->pipeline(
           $dm->createAggregationBuilder('Document\Order')->group()
               ->field('id')
               ->expression('$customer')
               ->field('lowestValue')
               ->min('$price')
               ->field('highestValue')
               ->max('$price')
);

The above code works.

{ "_id" : "1", "lowestValue" : 0,   "highestValue" : 120 }
{ "_id" : "2", "lowestValue" : 150, "highestValue" : 150 }

I want to ignore orders with a price of 0 or null.

Desired result:

{ "_id" : "1", "lowestValue" : 100, "highestValue" : 120 }
{ "_id" : "2", "lowestValue" : 150, "highestValue" : 150 }

Is this possible?
Can I use $cond (aggregation) ?

{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }

https://docs.mongodb.com/manual/reference/operator/aggregation/cond/

MongoDB 4.2
MongoDB ODM 2.0.3

3 Answers3

1

just begin your pipeline with a $gt : 0....that starts the data set with valid docs...

Cahaba Data
  • 624
  • 1
  • 4
  • 4
0

as suggested by Cahaba Data, filter out orders with a 0 price before grouping.

db.orders.aggregate([
    {
        $match: { price: { $gt: 0 } }
    },
    {
        $group: {
            _id: "$customer",
            lowestValue: { $min: "$price" },
            highestValue: { $max: "$price" }
        }
    }
])
Dĵ ΝιΓΞΗΛψΚ
  • 5,068
  • 3
  • 13
  • 26
0

Thanks for the replies. I found another solution.

db.orders.aggregate([
  {
    $group: {
      _id: "$customer",
      lowestValue: {
        $min: {
          $cond: [{
              $gt: ["$price", 0]
            }, "$price", null]
        }
      }
    }
  }
]);

Doctrine Aggregation Builder
...

->field('lowestValue')
->min($builder->expr()->cond($builder->expr()->gt('$price', 0), '$price', null))