gpt4 book ai didi

mongodb - golang中的条件聚合查询

转载 作者:IT王子 更新时间:2023-10-29 02:14:43 24 4
gpt4 key购买 nike

我正在使用 golang 和 mongodb。我的 attendance 集合看起来像这样 -

{
"_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
}
]
}

我想获取每个学生的百分比报告,作为对象数组,例如:

[{"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
}]

我的条件如下

college_id,stream,semester,section,subject,startingdate and enddate

最佳答案

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

这是由于不正确的 bson.M用法。如果它是一个字符串(单个值),则不需要创建 bson 映射。所以您可以将其更新为:

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

Go 中的聚合管道等效于:

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"}},
}

我建议结帐MongoDB mgo driver page用于示例和引用。

关于mongodb - golang中的条件聚合查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36515708/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com