How to use aggregation function mongo db-query

前端 未结 2 672
悲哀的现实
悲哀的现实 2021-01-27 07:19

I am new in MongoDB and I would like to use the aggregation function where I want to check type == topic and get the following output

E

相关标签:
2条回答
  • 2021-01-27 07:29

    Try to unwind the LearningNodes array and then count them by grouping them together

    db.PedagogyNodes.aggregate([
        {
           $unwind:"$contentNodes.LearningNodes"
        },
        {
            $group:
            {
                _id:"$contentNodes.LearningNodes",
                count:{$sum:1}
            }
        }
    ])
    

    In case you need to do any matches you can use the $match stage

    db.PedagogyNodes.aggregate([
        {
            $match:{type:"topic"}
        },
        {
           $unwind:"$contentNodes.LearningNodes"
        },
        {
            $group:
            {
                _id:"$contentNodes.LearningNodes",
                count:{$sum:1}
            }
        }
    ])
    

    Answering the edited question =>

    You were not able to view the output on the console since mongoshell does not print script output on the screen. To do this, do the following:

    var result =  records.PedagogyVersions.aggregate([......]);
    
    result.forEach(function(resultDoc){
        print(tojson(resultDoc))
    })
    
    0 讨论(0)
  • 2021-01-27 07:35

    To see the result of your aggregation you have to pass the callback to be executed as parameter.

    records.PedagogyVersions.aggregate([
            {
                $match:{_id:latestVersion} // Step 4
            },
            {
               $unwind:"$contentNodes.LearningNodes"
            },
            {
                $group:
                {
                    _id:"$contentNodes.LearningNodes",
                    count:{$sum:1}
                }
            }
        ], function(err, results) {
             console.log(results);
        });
    
    0 讨论(0)
提交回复
热议问题