嵌套数组元素的mongodb $ group

时间:2017-10-03 05:37:15

标签: mongodb aggregate

对于给定的问题,我有以下mongodb集合(questionanswers)

JsonConvert.DefaultSettings = () =>
{
    var settings = new JsonSerializerSettings();
    settings.Converters.Add(new GuidConverterCustom());
    return settings;
};

我需要cnt per sr no,它位于嵌套数组元素中。 预计是:

Srno ===> CNT

1 ===> 2

2 ===> 3

我正在尝试以下查询

{ 
"_id" : { "$oid" : "59cda8b730a0131cfafc9101" }, 
"questionId" : { "$oid" : "59cb7b85c854036fec173267" }, 
"userQuestionAnswerDetails" : [ { "srno" : 1, "correct_yn" : false}, { 
 "srno" : 2, "correct_yn" : false} ] 
}

{ 
"_id" : { "$oid" : "59cdb1b930a0131cfafc9102" }, 
"questionId" : { "$oid" : "59cb7b85c854036fec173267" }, 
"userQuestionAnswerDetails" : [ { "srno" : 2, "correct_yn" : false} ] 
}

{ 
"_id" : { "$oid" : "59cdbb1b30a0131cfafc9105" }, 
"questionId" : { "$oid" : "59cb7b85c854036fec173267" }, 
"userQuestionAnswerDetails" : [ { "srno" : 2, "correct_yn" : false} ] 
}

{ 
"_id" : { "$oid" : "59cdd26a30a0131cfafc9107" }, 
"questionId" : { "$oid" : "59cb7b85c854036fec173267" }, 
"userQuestionAnswerDetails" : [ { "srno" : 1, "correct_yn" : false} ] 
}

以上查询给出了类似下面的内容:

db.questionanswers.aggregate([
{
    $match:{
        $and: [
            {questionId: ObjectId("59cb7b85c854036fec173267")}
        ]       
    }
},
{
    $group : {_id : {questionId:"$questionId", userQuestionAnswerDetails: "$userQuestionAnswerDetails.srno"}, num_tutorial : {$sum : 1}}
}
])

相当于 Srno ===> CNT

1,2 ===> 1

1 ===> 1

2 ===> 2

如何修改$ group以达到预期效果?提前谢谢。

1 个答案:

答案 0 :(得分:2)

您可以通过添加$unwind阶段来实现。

db.questionanswers.aggregate([
{
    $match:{
        $and: [
            {questionId: ObjectId("59cb7b85c854036fec173267")}
        ]       
    }
}
,{
    $unwind: "$userQuestionAnswerDetails" 
}
,{
    $group : {_id :  {questionId:"$questionId", userQuestionAnswerDetails: "$userQuestionAnswerDetails.srno"}, num_tutorial : {$sum : 1}}
}
])

结果:

{ "_id" : { "questionId" : ObjectId("59cb7b85c854036fec173267"), "userQuestionAnswerDetails" : 2 }, "num_tutorial" : 3 }
{ "_id" : { "questionId" : ObjectId("59cb7b85c854036fec173267"), "userQuestionAnswerDetails" : 1 }, "num_tutorial" : 2 }