我具有以下文档结构,并且我的汇总花了很长时间。 以下是存储在Mongo中的JSON代码片段。
"project_id" : ObjectId("5c32fa9ffb6fc0600bda7b53"),
"campaign_id" : ObjectId("5c5cecd860d3f82c64b1195a"),
"respondent_id" : "5c5cecd860d3f82c64b1195b",
"status" : "Complete",
"demo1Key" : "gender",
"demo1Value" : "2", // these values are till 10
"responses" : [ // this is a dynamic array with the below properties
{
"_id" : ObjectId("5c5cecd860d3f82c64b11a54"),
"question" : "Question Text ",
"answer" : [ // This can be an array or a single text value
{
"id" : 10001,
"option" : "1",
"answer" : "1"
}
]
}]
在我的nodejs应用程序中,我正在尝试汇总如下所述的结果。
var groupById = { "optionText": "$responses.answer.answer", "question": "$responses.question" };
// create the group by id based on the maximum possible demographics for a single question option.
for (var i = 0; i <=10; i++) {
groupById[`demo${i}Key`] = `$demo${i}Key`
groupById[`demo${i}Value`] = `$demo${i}Value`
}
const aggregatorOpts = [
{
$match: {
$and: [
{
"project_id": new mongoose.Types.ObjectId(projId)
},
{ "status": "Complete" },
]
}
},
{
$unwind: "$responses"
},
{
$unwind: "$responses.answer"
},
{
$group: {
_id: groupById,
count: { $sum: 1 }
}
},
]
let dbData = await Respondent.aggregate(aggregatorOpts)
我尝试运行分析器,并在文档上添加了一些索引,即:resentent_id,project_id,campaign_id,状态