2

Here's my collection [test].

{"_id" : "Test1", "enabled": "on", "value" : 10},
{"_id" : "Test2", "enabled": "on", "value" : 50},
{"_id" : "Test3", "enabled": "on", "value" : 10},
{"_id" : "Test4", "value" : 5},
{"_id" : "Test5", "value" : 2}

I would like to get all the total of the value and total value of the field with "enabled":"on" like these:

Desired result:

[ { _id: null, totalValue: 77, totalEnabled: 70 } ]

Here's what i have so far but no luck.

db.collection('test').aggregate({
    $group: {
          _id: null,
          totalValue : {
              $sum: "$value"
          },
          totalEnabled: $sum : {"enabled":{$exists:true}}
      }
  }, function(err, result) {
    if (err) return console.dir(err)

    console.log(result);
});

1 Answer 1

3

You were close but $exists doesn't function is aggregation and has a different function. What you were looking for is $cond

db.items.aggregate([
    {$group: { 
        _id: null,
         totalValue: {$sum: "$value"}, 
         enabledValue: {$sum: {
             $cond: [
                 // Condition to test 
                 {$eq: ["$enabled", "on"] },
                 // True
                 "$value",
                 // False
                 0
            ] 
         }}
    }}
])

The usage is to provide a different value depending on whether the condition is evaluated to true or false.

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

2 Comments

That's more like it! I was trying to figure what your code does until you commented out the condition structure. Thanks!
@per.eight Glad that helped and that coming back for the edit was worthwhile. That is how I usually do it in these types of questions.

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.