我如何排序addtoset分组结果mongoDB查询

时间:2016-11-10 11:10:25

标签: mongodb sorting

目前我有以下内容:

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虽然很有用,但在分组方面并没有提供太多想法。

0 个答案:

没有答案