0

I have a document in mongodb whose schema is like this:

{ japanese3: 
   { '0': 
     {"japanese3a": 100,  "japanese3b": 100,  "japanese3c": 100} 
   } 
}

I want to get the sum of the values of japanese3a, japanese3b and japanese3c, which is 300.

This is what I have tried to get the sum but everytime I try it, the console shows nothing.

          var docs = await db.collection("myCollection")
           .aggregate([
              {$project: {_id:1, username:1, group:1, japanese3:1}},
              {$match: {username: username}},
              {$unwind: "$japanese3"}, 
              {$addFields:
               {total:
                {$sum:
                 {$map:
                  {input:
                   {$objectToArray:"$japanese3"}, as: "kv", in: "$$kv.v"
                  }
                 }
                }
               }
              }                          
           ])
          .toArray(function(err, result){
                 if (err) console.log("Didn't work");
                 console.log(result);
                 res.end(result);
           }) 
      }                       
 }); 

EDITED: I made an error in displaying the script and the document layout.

Honeybear65
  • 311
  • 1
  • 10
  • 1
    What is the expected output? Something like [this](https://mongoplayground.net/p/Qobrm-MZZko) ? – J.F. Feb 14 '21 at 09:58
  • Yes, something like that. I want the output to be a number, "300", which is the sum, or some statement like ```'"total" is: 300'```. I had trouble putting "total" in the console.log statement, so I just left it as "result". – Honeybear65 Feb 14 '21 at 10:41
  • 1
    [This](https://mongoplayground.net/p/KcOF1bMKnkc) example? – J.F. Feb 14 '21 at 10:50
  • I asked the wrong question but your answer is correct in the context of how the question was asked. I meant to show ```japanese3: {{Object}, {Object}, {Object}}``` Your answer helped me find a solution to a similar question I asked here: [link](https://stackoverflow.com/questions/66220099/how-to-find-the-sum-of-values-that-are-inside-a-nested-array-using-mongodb-aggre) that also involves a nested array @J.F. – Honeybear65 Feb 16 '21 at 08:54

1 Answers1

0

The document to be worked on is below. It is nested objects: an object (key-value pairs with the value being 100) is nested within an object ('0') (this is written as a string), and this is nested inside another object ("japanese3"). The username is used as a query to get the right document.

{ japanese3: 
   { '0': 
     {"japanese3a": 100,  "japanese3b": 100,  "japanese3c": 100} 
   } 
}

Aim is to sum the number values in the most deeply nested object, so the desired result is "300".

The script is:

         .aggregate([
           {$match: {username: username}}, //finds the document by username
           {$set: {"japanese_array":{$objectToArray: "$japanese3.0"}}}, // all fields have the same name now (k, v)
           {$project: {_id:0, total:{$sum: "$japanese_array2.v"}}}// sum up the "v" fields                                     
       ])
        .toArray(function(err, result){
          if (err)
            console.log("Failed");
            console.log(result); 
            res.send({ status: true, msg: result[0].total}); //result shows up as a number, in this case: 300
    });                            
 });
Honeybear65
  • 311
  • 1
  • 10