目前我有以下内容:
db.questionanswers.aggregate(
[
{
$group : { _id : {sessionId: "$sessionId", quizId: "$quizId" },
sessionId: {$first: "$sessionId"},
quizId: { $first: "$quizId"},
sessionStarted: {$first: "$created"},
QuestionSubmitted: {$last: "$created"},
answer: {$addToSet: "$answer"} }
},
]
)
尝试了$ sort,$ each,$ push,$ unwind,$ orderby的多种组合后,我现在无法对answer
字段进行排序,答案仍然在已定义$group
。
汇总自:
{
"_id" : ObjectId("xxx"),
"quizId" : "xxx",
"sessionId" : "xxx",
"questionId" : "q1",
"answer" : "answer a",
"created" : ISODate("2015-12-xxx"),
"__v" : 0
},
{
"_id" : ObjectId("xxx"),
"quizId" : "xxx",
"sessionId" : "xxx",
"questionId" : "q2",
"answer" : "answer b",
"created" : ISODate("2015-12-xxx"),
"__v" : 0
}, // etc //
使用mongoDB的$out
输出:
{
"_id" : {
"quizId" : "xxx",
"sessionId" : "xxx",
},
"sessionStarted" : "2015-12-xxx",
"QuestionsSubmitted" : "2015-12-xxx"
"answer" : {
"0" : "answer a",
"1" : "answer b"
// etc //
}
}
This similar answer虽然很有用,但在分组方面并没有提供太多想法。