Conditional $sum in MongoDBHow to $match and then accumulate within $group stage in MongoDB aggregationUsing $sum and $cond to get $sum of values, not sum of instances in mongoCOUNT ITEMS BY MATCH IN MONGODBHow to perform this mongo aggregation?How to group by multiple times with different fields in aggregate function of mongodb?How to right join two NoSQL queries together with PymongoMongodb aggregation framework project with conditionsMongoDB $group and explicit group formation with computed columnHow can i calculate price positive and negative price using mongodb or robomongo?Mongo aggregation filterHow to query MongoDB with “like”?Update MongoDB field using value of another fieldRetrieve only the queried element in an object array in MongoDB collectionHow do I drop a MongoDB database from the command line?How does MongoDB sort records when no sort order is specified?Is it possible to flatten MongoDB result query?$add with some fields as Null returning sum value as NullFinding a user-defined column from collection without groupingMax and group by in MongodbMongoDB aggregation group by similar string

Has the Hulk always been able to talk?

Install LibreOffice-Writer Only not LibreOffice whole package

Desolate vs deserted

Will 700 more planes a day fly because of the Heathrow expansion?

How to ask systemd to not start a system service on boot?

What are the advantages of luxury car brands like Acura/Lexus over their sibling non-luxury brands Honda/Toyota?

Where to draw the line between quantum mechanics theory and its interpretation(s)?

3D Volume in TIKZ

Why do people keep telling me that I am a bad photographer?

Nested loops to process groups of pictures

Are the Night's Watch still required?

Is it normal for gliders not to have attitude indicators?

To kill a cuckoo

What do "Sech" and "Vich" mean in this sentence?

Snap victim memorial reference in Avengers: Endgame

Are there terms in German for different skull shapes?

What to use instead of cling film to wrap pastry

Python 3 - simple temperature program

How long would it take for people to notice a mass disappearance?

Definition of conditional probability and a problem.

Is an HNN extension of a virtually torsion-free group virtually torsion-free?

getline() vs. fgets(): Control memory allocation

Prove that a definite integral is an infinite sum

Start job from another SQL server instance



Conditional $sum in MongoDB


How to $match and then accumulate within $group stage in MongoDB aggregationUsing $sum and $cond to get $sum of values, not sum of instances in mongoCOUNT ITEMS BY MATCH IN MONGODBHow to perform this mongo aggregation?How to group by multiple times with different fields in aggregate function of mongodb?How to right join two NoSQL queries together with PymongoMongodb aggregation framework project with conditionsMongoDB $group and explicit group formation with computed columnHow can i calculate price positive and negative price using mongodb or robomongo?Mongo aggregation filterHow to query MongoDB with “like”?Update MongoDB field using value of another fieldRetrieve only the queried element in an object array in MongoDB collectionHow do I drop a MongoDB database from the command line?How does MongoDB sort records when no sort order is specified?Is it possible to flatten MongoDB result query?$add with some fields as Null returning sum value as NullFinding a user-defined column from collection without groupingMax and group by in MongodbMongoDB aggregation group by similar string






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








32















My collection in mongodb is similar to the following table in SQL:



Sentiments(Company,Sentiment)



Now, I need to execute a query like this:



SELECT
Company,
SUM(CASE WHEN Sentiment >0 THEN Sentiment ELSE 0 END) AS SumPosSenti,
SUM(CASE WHEN Sentiment <0 THEN Sentiment ELSE 0 END) AS SumNegSenti
FROM Sentiments
GROUP BY Company


What should I do to write this query in Mongo? I am stuck at the following query:



db.Sentiments.aggregate(
$project: _id:0, Company:1, Sentiment: 1 ,
$group: _id: "$Company", SumPosSenti: $sum: ? , SumNegSenti: $sum: ?
);









share|improve this question



















  • 1





    You might be able to use a $cond in the sum: docs.mongodb.org/manual/reference/aggregation/… but it sounds like a butchery of speed and scalable querying, I can imagine this query was slow in SQL and will be slow here on a medium result set

    – Sammaye
    Dec 31 '12 at 14:18












  • @Sammaye I am trying to replace '?' with $cond: Sentiment: $gte: 0 . But that looks like a wrong syntax.. I'm not getting any output.

    – Aafreen Sheikh
    Dec 31 '12 at 14:30






  • 2





    $cond works like an if statement exactly like a case, so the first expression would be: Sentiment >0 and then Sentiment and then 0 for the first $cond in the first $sum

    – Sammaye
    Dec 31 '12 at 14:31

















32















My collection in mongodb is similar to the following table in SQL:



Sentiments(Company,Sentiment)



Now, I need to execute a query like this:



SELECT
Company,
SUM(CASE WHEN Sentiment >0 THEN Sentiment ELSE 0 END) AS SumPosSenti,
SUM(CASE WHEN Sentiment <0 THEN Sentiment ELSE 0 END) AS SumNegSenti
FROM Sentiments
GROUP BY Company


What should I do to write this query in Mongo? I am stuck at the following query:



db.Sentiments.aggregate(
$project: _id:0, Company:1, Sentiment: 1 ,
$group: _id: "$Company", SumPosSenti: $sum: ? , SumNegSenti: $sum: ?
);









share|improve this question



















  • 1





    You might be able to use a $cond in the sum: docs.mongodb.org/manual/reference/aggregation/… but it sounds like a butchery of speed and scalable querying, I can imagine this query was slow in SQL and will be slow here on a medium result set

    – Sammaye
    Dec 31 '12 at 14:18












  • @Sammaye I am trying to replace '?' with $cond: Sentiment: $gte: 0 . But that looks like a wrong syntax.. I'm not getting any output.

    – Aafreen Sheikh
    Dec 31 '12 at 14:30






  • 2





    $cond works like an if statement exactly like a case, so the first expression would be: Sentiment >0 and then Sentiment and then 0 for the first $cond in the first $sum

    – Sammaye
    Dec 31 '12 at 14:31













32












32








32


8






My collection in mongodb is similar to the following table in SQL:



Sentiments(Company,Sentiment)



Now, I need to execute a query like this:



SELECT
Company,
SUM(CASE WHEN Sentiment >0 THEN Sentiment ELSE 0 END) AS SumPosSenti,
SUM(CASE WHEN Sentiment <0 THEN Sentiment ELSE 0 END) AS SumNegSenti
FROM Sentiments
GROUP BY Company


What should I do to write this query in Mongo? I am stuck at the following query:



db.Sentiments.aggregate(
$project: _id:0, Company:1, Sentiment: 1 ,
$group: _id: "$Company", SumPosSenti: $sum: ? , SumNegSenti: $sum: ?
);









share|improve this question
















My collection in mongodb is similar to the following table in SQL:



Sentiments(Company,Sentiment)



Now, I need to execute a query like this:



SELECT
Company,
SUM(CASE WHEN Sentiment >0 THEN Sentiment ELSE 0 END) AS SumPosSenti,
SUM(CASE WHEN Sentiment <0 THEN Sentiment ELSE 0 END) AS SumNegSenti
FROM Sentiments
GROUP BY Company


What should I do to write this query in Mongo? I am stuck at the following query:



db.Sentiments.aggregate(
$project: _id:0, Company:1, Sentiment: 1 ,
$group: _id: "$Company", SumPosSenti: $sum: ? , SumNegSenti: $sum: ?
);






sql mongodb mongodb-query aggregation-framework






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 21 '17 at 20:47









Brad Larson♦

162k41365545




162k41365545










asked Dec 31 '12 at 14:12









Aafreen SheikhAafreen Sheikh

2,11752639




2,11752639







  • 1





    You might be able to use a $cond in the sum: docs.mongodb.org/manual/reference/aggregation/… but it sounds like a butchery of speed and scalable querying, I can imagine this query was slow in SQL and will be slow here on a medium result set

    – Sammaye
    Dec 31 '12 at 14:18












  • @Sammaye I am trying to replace '?' with $cond: Sentiment: $gte: 0 . But that looks like a wrong syntax.. I'm not getting any output.

    – Aafreen Sheikh
    Dec 31 '12 at 14:30






  • 2





    $cond works like an if statement exactly like a case, so the first expression would be: Sentiment >0 and then Sentiment and then 0 for the first $cond in the first $sum

    – Sammaye
    Dec 31 '12 at 14:31












  • 1





    You might be able to use a $cond in the sum: docs.mongodb.org/manual/reference/aggregation/… but it sounds like a butchery of speed and scalable querying, I can imagine this query was slow in SQL and will be slow here on a medium result set

    – Sammaye
    Dec 31 '12 at 14:18












  • @Sammaye I am trying to replace '?' with $cond: Sentiment: $gte: 0 . But that looks like a wrong syntax.. I'm not getting any output.

    – Aafreen Sheikh
    Dec 31 '12 at 14:30






  • 2





    $cond works like an if statement exactly like a case, so the first expression would be: Sentiment >0 and then Sentiment and then 0 for the first $cond in the first $sum

    – Sammaye
    Dec 31 '12 at 14:31







1




1





You might be able to use a $cond in the sum: docs.mongodb.org/manual/reference/aggregation/… but it sounds like a butchery of speed and scalable querying, I can imagine this query was slow in SQL and will be slow here on a medium result set

– Sammaye
Dec 31 '12 at 14:18






You might be able to use a $cond in the sum: docs.mongodb.org/manual/reference/aggregation/… but it sounds like a butchery of speed and scalable querying, I can imagine this query was slow in SQL and will be slow here on a medium result set

– Sammaye
Dec 31 '12 at 14:18














@Sammaye I am trying to replace '?' with $cond: Sentiment: $gte: 0 . But that looks like a wrong syntax.. I'm not getting any output.

– Aafreen Sheikh
Dec 31 '12 at 14:30





@Sammaye I am trying to replace '?' with $cond: Sentiment: $gte: 0 . But that looks like a wrong syntax.. I'm not getting any output.

– Aafreen Sheikh
Dec 31 '12 at 14:30




2




2





$cond works like an if statement exactly like a case, so the first expression would be: Sentiment >0 and then Sentiment and then 0 for the first $cond in the first $sum

– Sammaye
Dec 31 '12 at 14:31





$cond works like an if statement exactly like a case, so the first expression would be: Sentiment >0 and then Sentiment and then 0 for the first $cond in the first $sum

– Sammaye
Dec 31 '12 at 14:31












3 Answers
3






active

oldest

votes


















47














As Sammaye suggested, you need to use the $cond aggregation projection operator to do this:



db.Sentiments.aggregate(
$project:
_id: 0,
Company: 1,
PosSentiment: $cond: [$gt: ['$Sentiment', 0], '$Sentiment', 0],
NegSentiment: $cond: [$lt: ['$Sentiment', 0], '$Sentiment', 0]
,
$group:
_id: "$Company",
SumPosSentiment: $sum: '$PosSentiment',
SumNegSentiment: $sum: '$NegSentiment'
);





share|improve this answer
































    28














    Starting from version 3.4, we can use the $switch operator which allows logical condition processing in the $group stage. Of course we still need to use the $sum accumulator to return the sum.



    db.Sentiments.aggregate(
    [
    "$group":
    "_id": "$Company",
    "SumPosSenti":
    "$sum":
    "$switch":
    "branches": [

    "case": "$gt": [ "$Sentiment", 0 ] ,
    "then": "$Sentiment"

    ],
    "default": 0


    ,
    "SumNegSenti":
    "$sum":
    "$switch":
    "branches": [

    "case": "$lt": [ "$Sentiment", 0 ] ,
    "then": "$Sentiment"

    ],
    "default": 0




    ]
    )



    If you have not yet migrated your mongod to 3.4 or newer, then note that the $project stage in this answer is redundant because the $cond operator returns a numeric value which means that you can $group your documents and apply $sum to the $cond expression.



    This will improve the performance in your application especially for large collection.



    db.Sentiments.aggregate(
    [
    '$group':
    '_id': '$Company',
    'PosSentiment':
    '$sum':
    '$cond': [
    '$gt': ['$Sentiment', 0],
    '$Sentiment',
    0
    ]

    ,
    'NegSentiment':
    '$sum':
    '$cond': [
    '$lt': ['$Sentiment', 0],
    '$Sentiment',
    0
    ]



    ]
    )



    Consider a collection Sentiments with the following documents:



     "Company": "a", "Sentiment" : 2 
    "Company": "a", "Sentiment" : 3
    "Company": "a", "Sentiment" : -1
    "Company": "a", "Sentiment" : -5


    The aggregation query produces:



     "_id" : "a", "SumPosSenti" : 5, "SumNegSenti" : -6 





    share|improve this answer




















    • 1





      Nice, exactly what I was looking for!

      – Evertvdw
      Jan 27 '18 at 8:33











    • Wow! That was very helpful. Totally did the trick for me.

      – tonejac
      Jun 28 '18 at 6:01


















    2














    Explaining the snippets above, that uses the array syntax:



    PosSentiment: $cond: [$gt: ['$Sentiment', 0], '$Sentiment', 0]


    is equal to:



    PosSentiment: $cond: if: $gt: ['$Sentiment', 0], then: '$Sentiment', else: 0 


    The array syntax summarizes the long syntax to just $cond: [if, then, else]






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14102596%2fconditional-sum-in-mongodb%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      47














      As Sammaye suggested, you need to use the $cond aggregation projection operator to do this:



      db.Sentiments.aggregate(
      $project:
      _id: 0,
      Company: 1,
      PosSentiment: $cond: [$gt: ['$Sentiment', 0], '$Sentiment', 0],
      NegSentiment: $cond: [$lt: ['$Sentiment', 0], '$Sentiment', 0]
      ,
      $group:
      _id: "$Company",
      SumPosSentiment: $sum: '$PosSentiment',
      SumNegSentiment: $sum: '$NegSentiment'
      );





      share|improve this answer





























        47














        As Sammaye suggested, you need to use the $cond aggregation projection operator to do this:



        db.Sentiments.aggregate(
        $project:
        _id: 0,
        Company: 1,
        PosSentiment: $cond: [$gt: ['$Sentiment', 0], '$Sentiment', 0],
        NegSentiment: $cond: [$lt: ['$Sentiment', 0], '$Sentiment', 0]
        ,
        $group:
        _id: "$Company",
        SumPosSentiment: $sum: '$PosSentiment',
        SumNegSentiment: $sum: '$NegSentiment'
        );





        share|improve this answer



























          47












          47








          47







          As Sammaye suggested, you need to use the $cond aggregation projection operator to do this:



          db.Sentiments.aggregate(
          $project:
          _id: 0,
          Company: 1,
          PosSentiment: $cond: [$gt: ['$Sentiment', 0], '$Sentiment', 0],
          NegSentiment: $cond: [$lt: ['$Sentiment', 0], '$Sentiment', 0]
          ,
          $group:
          _id: "$Company",
          SumPosSentiment: $sum: '$PosSentiment',
          SumNegSentiment: $sum: '$NegSentiment'
          );





          share|improve this answer















          As Sammaye suggested, you need to use the $cond aggregation projection operator to do this:



          db.Sentiments.aggregate(
          $project:
          _id: 0,
          Company: 1,
          PosSentiment: $cond: [$gt: ['$Sentiment', 0], '$Sentiment', 0],
          NegSentiment: $cond: [$lt: ['$Sentiment', 0], '$Sentiment', 0]
          ,
          $group:
          _id: "$Company",
          SumPosSentiment: $sum: '$PosSentiment',
          SumNegSentiment: $sum: '$NegSentiment'
          );






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Aug 6 '16 at 13:07

























          answered Dec 31 '12 at 14:43









          JohnnyHKJohnnyHK

          216k42458380




          216k42458380























              28














              Starting from version 3.4, we can use the $switch operator which allows logical condition processing in the $group stage. Of course we still need to use the $sum accumulator to return the sum.



              db.Sentiments.aggregate(
              [
              "$group":
              "_id": "$Company",
              "SumPosSenti":
              "$sum":
              "$switch":
              "branches": [

              "case": "$gt": [ "$Sentiment", 0 ] ,
              "then": "$Sentiment"

              ],
              "default": 0


              ,
              "SumNegSenti":
              "$sum":
              "$switch":
              "branches": [

              "case": "$lt": [ "$Sentiment", 0 ] ,
              "then": "$Sentiment"

              ],
              "default": 0




              ]
              )



              If you have not yet migrated your mongod to 3.4 or newer, then note that the $project stage in this answer is redundant because the $cond operator returns a numeric value which means that you can $group your documents and apply $sum to the $cond expression.



              This will improve the performance in your application especially for large collection.



              db.Sentiments.aggregate(
              [
              '$group':
              '_id': '$Company',
              'PosSentiment':
              '$sum':
              '$cond': [
              '$gt': ['$Sentiment', 0],
              '$Sentiment',
              0
              ]

              ,
              'NegSentiment':
              '$sum':
              '$cond': [
              '$lt': ['$Sentiment', 0],
              '$Sentiment',
              0
              ]



              ]
              )



              Consider a collection Sentiments with the following documents:



               "Company": "a", "Sentiment" : 2 
              "Company": "a", "Sentiment" : 3
              "Company": "a", "Sentiment" : -1
              "Company": "a", "Sentiment" : -5


              The aggregation query produces:



               "_id" : "a", "SumPosSenti" : 5, "SumNegSenti" : -6 





              share|improve this answer




















              • 1





                Nice, exactly what I was looking for!

                – Evertvdw
                Jan 27 '18 at 8:33











              • Wow! That was very helpful. Totally did the trick for me.

                – tonejac
                Jun 28 '18 at 6:01















              28














              Starting from version 3.4, we can use the $switch operator which allows logical condition processing in the $group stage. Of course we still need to use the $sum accumulator to return the sum.



              db.Sentiments.aggregate(
              [
              "$group":
              "_id": "$Company",
              "SumPosSenti":
              "$sum":
              "$switch":
              "branches": [

              "case": "$gt": [ "$Sentiment", 0 ] ,
              "then": "$Sentiment"

              ],
              "default": 0


              ,
              "SumNegSenti":
              "$sum":
              "$switch":
              "branches": [

              "case": "$lt": [ "$Sentiment", 0 ] ,
              "then": "$Sentiment"

              ],
              "default": 0




              ]
              )



              If you have not yet migrated your mongod to 3.4 or newer, then note that the $project stage in this answer is redundant because the $cond operator returns a numeric value which means that you can $group your documents and apply $sum to the $cond expression.



              This will improve the performance in your application especially for large collection.



              db.Sentiments.aggregate(
              [
              '$group':
              '_id': '$Company',
              'PosSentiment':
              '$sum':
              '$cond': [
              '$gt': ['$Sentiment', 0],
              '$Sentiment',
              0
              ]

              ,
              'NegSentiment':
              '$sum':
              '$cond': [
              '$lt': ['$Sentiment', 0],
              '$Sentiment',
              0
              ]



              ]
              )



              Consider a collection Sentiments with the following documents:



               "Company": "a", "Sentiment" : 2 
              "Company": "a", "Sentiment" : 3
              "Company": "a", "Sentiment" : -1
              "Company": "a", "Sentiment" : -5


              The aggregation query produces:



               "_id" : "a", "SumPosSenti" : 5, "SumNegSenti" : -6 





              share|improve this answer




















              • 1





                Nice, exactly what I was looking for!

                – Evertvdw
                Jan 27 '18 at 8:33











              • Wow! That was very helpful. Totally did the trick for me.

                – tonejac
                Jun 28 '18 at 6:01













              28












              28








              28







              Starting from version 3.4, we can use the $switch operator which allows logical condition processing in the $group stage. Of course we still need to use the $sum accumulator to return the sum.



              db.Sentiments.aggregate(
              [
              "$group":
              "_id": "$Company",
              "SumPosSenti":
              "$sum":
              "$switch":
              "branches": [

              "case": "$gt": [ "$Sentiment", 0 ] ,
              "then": "$Sentiment"

              ],
              "default": 0


              ,
              "SumNegSenti":
              "$sum":
              "$switch":
              "branches": [

              "case": "$lt": [ "$Sentiment", 0 ] ,
              "then": "$Sentiment"

              ],
              "default": 0




              ]
              )



              If you have not yet migrated your mongod to 3.4 or newer, then note that the $project stage in this answer is redundant because the $cond operator returns a numeric value which means that you can $group your documents and apply $sum to the $cond expression.



              This will improve the performance in your application especially for large collection.



              db.Sentiments.aggregate(
              [
              '$group':
              '_id': '$Company',
              'PosSentiment':
              '$sum':
              '$cond': [
              '$gt': ['$Sentiment', 0],
              '$Sentiment',
              0
              ]

              ,
              'NegSentiment':
              '$sum':
              '$cond': [
              '$lt': ['$Sentiment', 0],
              '$Sentiment',
              0
              ]



              ]
              )



              Consider a collection Sentiments with the following documents:



               "Company": "a", "Sentiment" : 2 
              "Company": "a", "Sentiment" : 3
              "Company": "a", "Sentiment" : -1
              "Company": "a", "Sentiment" : -5


              The aggregation query produces:



               "_id" : "a", "SumPosSenti" : 5, "SumNegSenti" : -6 





              share|improve this answer















              Starting from version 3.4, we can use the $switch operator which allows logical condition processing in the $group stage. Of course we still need to use the $sum accumulator to return the sum.



              db.Sentiments.aggregate(
              [
              "$group":
              "_id": "$Company",
              "SumPosSenti":
              "$sum":
              "$switch":
              "branches": [

              "case": "$gt": [ "$Sentiment", 0 ] ,
              "then": "$Sentiment"

              ],
              "default": 0


              ,
              "SumNegSenti":
              "$sum":
              "$switch":
              "branches": [

              "case": "$lt": [ "$Sentiment", 0 ] ,
              "then": "$Sentiment"

              ],
              "default": 0




              ]
              )



              If you have not yet migrated your mongod to 3.4 or newer, then note that the $project stage in this answer is redundant because the $cond operator returns a numeric value which means that you can $group your documents and apply $sum to the $cond expression.



              This will improve the performance in your application especially for large collection.



              db.Sentiments.aggregate(
              [
              '$group':
              '_id': '$Company',
              'PosSentiment':
              '$sum':
              '$cond': [
              '$gt': ['$Sentiment', 0],
              '$Sentiment',
              0
              ]

              ,
              'NegSentiment':
              '$sum':
              '$cond': [
              '$lt': ['$Sentiment', 0],
              '$Sentiment',
              0
              ]



              ]
              )



              Consider a collection Sentiments with the following documents:



               "Company": "a", "Sentiment" : 2 
              "Company": "a", "Sentiment" : 3
              "Company": "a", "Sentiment" : -1
              "Company": "a", "Sentiment" : -5


              The aggregation query produces:



               "_id" : "a", "SumPosSenti" : 5, "SumNegSenti" : -6 






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Dec 21 '17 at 20:36

























              answered Aug 6 '16 at 7:10









              styvanestyvane

              37k1486108




              37k1486108







              • 1





                Nice, exactly what I was looking for!

                – Evertvdw
                Jan 27 '18 at 8:33











              • Wow! That was very helpful. Totally did the trick for me.

                – tonejac
                Jun 28 '18 at 6:01












              • 1





                Nice, exactly what I was looking for!

                – Evertvdw
                Jan 27 '18 at 8:33











              • Wow! That was very helpful. Totally did the trick for me.

                – tonejac
                Jun 28 '18 at 6:01







              1




              1





              Nice, exactly what I was looking for!

              – Evertvdw
              Jan 27 '18 at 8:33





              Nice, exactly what I was looking for!

              – Evertvdw
              Jan 27 '18 at 8:33













              Wow! That was very helpful. Totally did the trick for me.

              – tonejac
              Jun 28 '18 at 6:01





              Wow! That was very helpful. Totally did the trick for me.

              – tonejac
              Jun 28 '18 at 6:01











              2














              Explaining the snippets above, that uses the array syntax:



              PosSentiment: $cond: [$gt: ['$Sentiment', 0], '$Sentiment', 0]


              is equal to:



              PosSentiment: $cond: if: $gt: ['$Sentiment', 0], then: '$Sentiment', else: 0 


              The array syntax summarizes the long syntax to just $cond: [if, then, else]






              share|improve this answer



























                2














                Explaining the snippets above, that uses the array syntax:



                PosSentiment: $cond: [$gt: ['$Sentiment', 0], '$Sentiment', 0]


                is equal to:



                PosSentiment: $cond: if: $gt: ['$Sentiment', 0], then: '$Sentiment', else: 0 


                The array syntax summarizes the long syntax to just $cond: [if, then, else]






                share|improve this answer

























                  2












                  2








                  2







                  Explaining the snippets above, that uses the array syntax:



                  PosSentiment: $cond: [$gt: ['$Sentiment', 0], '$Sentiment', 0]


                  is equal to:



                  PosSentiment: $cond: if: $gt: ['$Sentiment', 0], then: '$Sentiment', else: 0 


                  The array syntax summarizes the long syntax to just $cond: [if, then, else]






                  share|improve this answer













                  Explaining the snippets above, that uses the array syntax:



                  PosSentiment: $cond: [$gt: ['$Sentiment', 0], '$Sentiment', 0]


                  is equal to:



                  PosSentiment: $cond: if: $gt: ['$Sentiment', 0], then: '$Sentiment', else: 0 


                  The array syntax summarizes the long syntax to just $cond: [if, then, else]







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Feb 23 '18 at 21:51









                  dpolicastrodpolicastro

                  39529




                  39529



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid …


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14102596%2fconditional-sum-in-mongodb%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

                      155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

                      Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?