0

I am using node.js and writing a script using the Express framework. I am using cloud Mongodb and don't have access to a mongo shell, so I can't check output easily. I have to put the result in an array, using the toArrray function, so that I can see what's being put out. Console.log helps but sometimes it shows just [] when it is an object, although I can see the properties within the object if I check Postman.

I have a document that I have been sending down an aggregation pipeline in mongodb and at this point, where I am stuck, the output that appears in res.send is this:

[ { japanese_array: [ {"k": "japanese3a", "v": { "question": "japanese3a", "value": 100}}, 
                      {"k": "japanese3b", "v": { "question": "japanese3b", "value": 100}}, 
                      {"k": "japanese3c", "v": { "question": "japanese3c", "value": 100}} ] } ]

I want to add the fields called "value", so the desired output is just a number (300).

It's taken a long time to arrive at this point as there was a lot of trouble following examples of solutions in Stackoverflow as they seem to use a lot of quotes (eg. "$project"), and if I copy the examples in my script, with the quotes included, the script does not work. I have to remove the quotes around $project, etc to get the thing working. I don't understand why putting quotes around certain words work for other people and it doesn't for me. I am using mongodb version 4.2.

I have checked other similar questions in stackoverflow for days, but none of the solutions work for me.

The one that was closest to answering it for me is from here: How to sum every fields in a sub document of MongoDB?

But it still does not work. I have tried summing "$japanese_array.v.value" in a $group expression but it's not working, and I am stuck at the point that's shown here.

Honeybear65
  • 311
  • 1
  • 10

1 Answers1

0

I solved the problem.

I did this additional stage to the pipeline:

{$project: {_id:0, "result":{$sum: "$japanese_array.v.value"}}}

I asked a similar question 2 days ago and the answer I got then How do you sum the values within an object which is a nested subdocument in mongodb using node.js? helped me find a solution here.

Honeybear65
  • 311
  • 1
  • 10