我需要回答这份文件的问题。
我尝试了以下查询,但我没有得到正确答案
db.player_quiz.aggregate({ $unwind:"$questions_answered"},{$group:{_id:ObjectId("5a3a567a8fb6e20f67cb10f7"),count:{$sum:1}}})
正确的回答是2但我得到15 ..请帮我解决。
答案 0 :(得分:1)
我有一个如下所示的集合 -
{
"_id" : ObjectId("5a4c68c8ea76fd79ec70c740"),
"address" : {
"building" : "1007",
"coord" : [
-73.856077,
40.848447
],
"street" : "Morris Park Ave",
"zipcode" : "10462"
},
"borough" : "Bronx",
"cuisine" : "Bakery",
"grades" : [
{
"date" : ISODate("2014-03-03T00:00:00Z"),
"grade" : "A",
"score" : 2
},
{
"date" : ISODate("2013-09-11T00:00:00Z"),
"grade" : "A",
"score" : 6
},
{
"date" : ISODate("2013-01-24T00:00:00Z"),
"grade" : "A",
"score" : 10
},
{
"date" : ISODate("2011-11-23T00:00:00Z"),
"grade" : "A",
"score" : 9
},
{
"date" : ISODate("2011-03-10T00:00:00Z"),
"grade" : "B",
"score" : 14
}
],
"name" : "Morris Park Bake Shop",
"restaurant_id" : "30075445"
}
要查找成绩的大小,我会使用它 -
db.location.aggregate([{$match:{_id:ObjectId("5a2f66c7a3811ba54bbaaabe")}},{$project:{'ans':{$size:'*$grades*'}}}])
在你的情况下用$ questions_answered替换$ grade。 希望这会有所帮助。
当您询问有关获得总和时 - 以下查询返回总和以及计数
db.location.aggregate([{
$match: {
_id: ObjectId("5a4c68c8ea76fd79ec70c740")//REPLACE THIS
}
}, {
$unwind: '$grades' //REPLACE THIS
}, {
$group: {
_id: "$_id",
'sum': {
$sum: '$grades.score'//REPLACE THIS
},
'doc': {
$push: '$grades' //REPLACE THIS
}
}
}, {
$project: {
'sum': '$sum',
'size': {
$size: '$doc'
}
}
}
])
结果
{ "_id" : ObjectId("5a4c68c8ea76fd79ec70c740"), "sum" : 41, "size" : 5 }