0

//Sample collection

db.grades.insertMany([{ _id: 1, quizzes: [ 1, 2, 3 ] },
{ _id: 2, quizzes: [ ] },
{ _id: 3, quizzes: [ 3, 8, 9 ] }])

Below is the query i am using and getting results. //Product of Sum

db.grades.aggregate(
   [
    { $project:
         { sumof:
            {
              $map:
                 {
                   input: "$quizzes",
                   as: "grade",
                   in: { $sum :[ "$$grade", "$$grade" ] }
                 }
            }
         }
      },

    {   $project :
        { "productOfSum":
            { $reduce :
                { input : '$sumof',
                    initialValue: 1,
                in : {$multiply :["$$value","$$this"]}
                }
            }
        }
    }   
    ]
)

The output of the query is as below.

{"_id":1,"productOfSum":48}
{"_id":2,"productOfSum":1}
{"_id":3,"productOfSum":1728}

Can any one advice how and why for "_id:2", value is coming as 1 even though array is null?

2
  • Because initialValue is 1 Commented Mar 15, 2019 at 12:30
  • however the array is null. Would multiplying a null array with 1, should it result with 1 or 0? Commented Mar 15, 2019 at 14:04

1 Answer 1

0

Try this: db.grades.aggregate( [

{$project:
{quizzes:
    {$cond:
        [{$eq: [{$size: "$quizzes"}, 0]} , [0], "$quizzes"] } 
    }
 },

{ $project:
     { sumof:
        {
          $map:
             {
               input: "$quizzes",
               as: "grade",
               in: { $sum :[ "$$grade", "$$grade" ] }
             }
        }
     }
  },

{   $project :
    { "productOfSum":
        { $reduce :
            { input : '$sumof',
                initialValue: 1,
            in : {$multiply :["$$value","$$this"]}
            }
        }
    }
}   
]

)

Sign up to request clarification or add additional context in comments.

2 Comments

You have to initialize empty arrays with 0 value
Please close your question by clicking the checkmark to the left of the answer that helped you most

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.