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
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.