dqyz48470 2016-04-09 10:43
浏览 409

Golang中的条件聚合查询

i am using golang and mongodb. my attendance collection looks like this -

{
    "_id" : ObjectId("5708156b51230e8edcb01fd1"),
    "college_id" : "tisl",
    "stream" : "CS",
    "semester" : "sem3",
    "section" : "A",
    "subject" : "PH301",
    "date" : ISODate("2016-04-08T20:32:42.547Z"),
    "teacher" : "Chandra Kanta Bhattacharya",
    "atndnc" : [ 
        {
            "rollno" : "13000112115",
            "name" : "Md Hossain Ahamed",
            "attend" : true
        }, 
        {
            "rollno" : "13000112116",
            "name" : "Md Sajid Tagala",
            "attend" : true
        }, 
        {
            "rollno" : "13000112117",
            "name" : "Nabarun  Roy",
            "attend" : false
        }, 
        {
            "rollno" : "13000112118",
            "name" : "Nikunj  Mundra",
            "attend" : true
        }
    ]
}

I want to get report for each student in percentage as an array of object like:

[{"rollno" : "13000112115",
            "name" : "Md Hossain Ahamed",
            "prcntg" : 80},
        {
            "rollno" : "13000112116",
            "name" : "Md Sajid Tagala",
            "prcntg" : 60
        }, 
        {
            "rollno" : "13000112117",
            "name" : "Nabarun  Roy",
            "prcntg" : 90
        }, 
        {
            "rollno" : "13000112118",
            "name" : "Nikunj  Mundra",
            "prcntg" : 65
        }]

and my conditions will be the following

college_id,stream,semester,section,subject,startingdate and enddate
  • 写回答

1条回答 默认 最新

  • dqp21271 2016-04-15 00:13
    关注

    bson.M{"$group":bson.M{"_id":{"rollno":bson.M{"$atndnc.rollno"}}}} in this line i am getting that error

    This is due to the incorrect bson.M usage. You don't need to create a bson map if its a string (single value). So you could update that to:

    bson.M{"$group":
        bson.M{"_id": bson.M{"rollno":"$atndnc.rollno"}}
    } 
    

    The equivalent of your aggregation pipeline in Go is below :

    pipeline := []bson.M{ 
            bson.M{"$match": 
                bson.M{"stream": "CS", "semester":"sem3", "section":"A"}},
            bson.M{"$unwind": "$atndnc"},
            bson.M{"$group": 
                bson.M{ "_id": bson.M{"rollno":"$atndnc.rollno", "name":"$atndnc.name"},     
                        "count":bson.M{"$sum":1},
                      },
            }, 
            bson.M{"$project": 
                bson.M{"_id":"$_id.rollno", "name":"$_id.name", "count":"$count"}},
            }
    

    I would recommend to checkout MongoDB mgo driver page for examples and references.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大