How to use aggregation function mongo db-query

前端 未结 2 708
悲哀的现实
悲哀的现实 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))
    })
    

提交回复
热议问题