Mongodb aggregate $push with $cond and $each

10,116

Solution 1

Please try it without $each as below

Item.aggregate(
    [{
        $group: {
          _id: "$_id",
          numbers: {
            $push: {
              $cond: { 
                if: { $gt: [ "$price.percent", 70 ] }, 
                then: [10,25,50,70] ,
                else: null,
              }
            }
          }
        }
      }]);

Solution 2

Provided answers will work but they'll add null to the array whenever else block gets executed & at the end you need to filter out the null values from the actual array (numbers) which is an additional step to do!

You can use $$REMOVE to conditionally exclude fields in MongoDB's $project.

Item.aggregate(
    [{
        $group: {
            _id: "$_id",
            numbers: { $push: { $cond: [{ $gt: ["$price.percent", 70] }, [10, 25, 50, 70], '$$REMOVE'] } } // With $$REMOVE nothing happens on else
        }
    }]);

REF: $cond

Share:
10,116

Related videos on Youtube

user1828780
Author by

user1828780

Updated on June 04, 2022

Comments

  • user1828780
    user1828780 almost 2 years

    I'm trying to use $cond to conditionally $push multiple integers onto a numbers array during an aggregate $group without any success. Here is my code:

    Item.aggregate(
        [
          {
            $group: {
              _id: "$_id",
              numbers: {
                $push: {
                  $cond: { 
                    if: { $gt: [ "$price.percent", 70 ] }, 
                    then: { $each: [10,25,50,70] },
                    else: null,
                  }
                }
              }
            }
          },
        ]
      )
      ...
    

    Is Mongo DB just not set up for this right now, or am I looking at this all wrong?