0

I have an object that has an array of page objects and each page object has an array of questions.

Ex object:

{
Id: 1,
UserId: 14,
Deleted: false,
Collaborators: [],
Title: "Awesome",
Pages: [{
    Id: 1,
    Title: 'Jank',
    Questions: [
        { Id: 1, Content: 'Ask me about it' },
        { Id: 2, Content: 'Ask me about it again' }
    ]
}, {
    Id: 2,
    Title: 'Janker',
    Questions: [
        { Id: 1, Content: 'Tell me about it' },
        { Id: 2, Content: 'Tell me about it again' }
    ]
}]
}

What I am trying to do is to get a count of all the questions for the entire bas object. I am not sure how to do that. I have tried to use aggregate and $sum the total questions and then do another function to $sum those all together to get a total for the entire object. Unfortunately my $sum is not working like I thought it would.

Ex code (nodejs):

var getQuestionCount = function(id) {
    var cursor = mongo.collection('surveys').aggregate([{
            $match: {
                $or: [{
                    "UserId": id
                }, {
                    "Collaborators": {
                        $in: [id]
                    }
                }]
            }
        }, {
            $match: {
                "Deleted": false
            }
        }, {
            $unwind: "$Pages"
        },
        { $group: { _id: null, number: { $sum: "$Pages.Questions" } } }
    ], function(err, result) {
        //This log just gives me [object Object], [object Object]
        console.log('q count ' + result);
    });
}

Any idea how to do this? My end result from the example object above would ideally return 4 as the question count for the whole object.

1 Answer 1

1

I'd try following shell query.

db.collection.aggregate([
  // filter out unwanted documents.
  {$match:{Id: 1}},

  // Unwind Pages collection to access Questions array
  {$unwind:"$Pages"},

  // Count items in Questions array
  {$project:{count: {$size:"$Pages.Questions"}}},

  // Finally sum items previously counted.
  {$group:{_id:"$_id", total: {$sum: "$count"}}}
])

Based on your sample document, it should return correct count of Questions.

{ 
    "_id" : ObjectId("57723bb8c10c41c41ff4897c"), 
    "total" : NumberInt(4)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you that worked great. The result is an array thought not a single object so i just did result[0].total

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.