给定集合中的以下项目,如何获得所有记录的id == 1的assessment.answer字段的平均值?此外,我需要返回subs []的第一个索引,每个记录像subs [0]
{
"_id" : ObjectId("57b5e55e8426706357a90728"),
"updatedAt" : ISODate("2016-08-20T00:21:16.497Z"),
"createdAt" : ISODate("2016-08-18T16:42:06.173Z"),
"password" : "password",
"email" : "test@user.com",
"lastName" : "User",
"firstName" : "Test",
"assessment" : [
{
"subs" : [
100,
100,
100,
100,
100
],
"answer" : 2,
"id" : 1
},
{
"subs" : [
80,
40,
100,
60,
20
],
"answer" : 2,
"id" : 2
},
{
"subs" : [
80,
20,
20,
20,
20
],
"answer" : 4,
"id" : 3
},
{
"subs" : [
80,
100,
60,
100,
100
],
"answer" : 5,
"id" : 4
},
{
"subs" : [
60,
100,
100,
100,
100
],
"answer" : 1,
"id" : 5
},
{
"subs" : [
100,
100,
100,
100,
100
],
"answer" : 3,
"id" : 6
},
{
"subs" : [
80,
20,
100,
80,
60
],
"answer" : 3,
"id" : 7
},
{
"subs" : [
20,
20,
20,
20,
20
],
"answer" : 4,
"id" : 8
},
{
"subs" : [
60,
60,
60,
60,
40
],
"answer" : 5,
"id" : 9
},
{
"subs" : [
60,
60,
60,
60,
40
],
"answer" : 3,
"id" : 10
},
{
"subs" : [
100,
100,
100,
100,
100
],
"answer" : 4,
"id" : 11
},
{
"subs" : [
80,
80,
80,
80,
80
],
"answer" : 1,
"id" : 12
},
{
"subs" : [
60,
60,
60,
60,
60
],
"answer" : 2,
"id" : 13
},
{
"subs" : [
40,
40,
40,
40,
40
],
"answer" : 3,
"id" : 14
},
{
"subs" : [
80,
20,
20,
20,
100
],
"answer" : 3,
"id" : 15
}
],
"__v" : 51
}
答案 0 :(得分:0)
var ids = [ 1, 2, 3, 4, 5 ];
var matchStage = { "$match": { "assessment.id": { "$in": ids } } };
db.accounts.aggregate(
[
matchStage,
{ "$unwind": "$assessment" },
matchStage,
{ "$group": {
"_id": null,
"avg": { "$avg": "$assessment.answer" }
}}
]
)
从MongoDB 3.2开始,您可以这样做:
db.accounts.aggregate(
[
matchStage,
{ "$project": {
"preAvg": {
"$avg": {
"$map": {
"input": {
"$filter": {
"input": "$assessment",
"as": "el",
"cond": { "$setIsSubset": [ [ "$$el.id" ], ids ] }
}
},
"as": "val",
"in": "$$val.answer"
}
}
}
}},
{ "$group": {
"_id": null,
"avg": { "$sum": "$preAvg" }
}}
]
)