$ group $内的$ Sort $ addToSet - MongoDB查询

时间:2016-11-03 11:20:05

标签: mongodb mongodb-query aggregation-framework

目前我有:

db.questionanswers.aggregate( 
  [ 
    sessionStarted: {$first: "$created"}, QuestionsSubmitted: {$last: "$created"}, answer: {$addToSet: "$answer"}}}
  ],
  {
    allowDiskUse: true
  }
)

汇总了一个对象列表,其中每个对象都有一个与quizID和sessionID相关的答案组。

在查看此Stackoverflow answer以对$ addToSet数组进行排序后,我将查询修改为:

db.questionanswers.aggregate( 
  [ 
    {$unwind: "$answer"},
    {$group : {_id : {sessionId: "$sessionId", quizID: "$quizId" }, answer: {$addToSet: "$answer"} }},
    {$unwind : "$answer"},
    {$sort : {"answer": 1}},
    {$group : { _id : {sessionId: "$sessionId", quizID: "$quizId" }, sessionStarted: {$first: "$created"}, QuestionsSubmitted: {$last: "$created"}, answer: {$push: "$answer"}}}
  ],
  {
    allowDiskUse: true
  }
)

我进入了Robomongo script executed successfully, but there are no results to show

我尝试从same answer above_id : null查询中切换_id : {sessionId: "$sessionId", quizID: "$quizId" },但它不会返回任何结果,除非在两者上使用_id : null并返回所有结果在一个巨大的组中排序的答案,这是有道理的,但它不是我所追求的。任何想法如何使用$addToSet对每个答案$group进行排序?

编辑:

汇总
{
  "_id" : ObjectId("xxx"),
  "quizId" : "xxx",
  "sessionId" : "xxx",
  "questionId" : "gender",
  "categoryId" : "1",
  "question" : "male or female",
  "answer" : "male",
  "created" : ISODate("2015-12-xxx"),
  "__v" : 0
},
{
  "_id" : ObjectId("xxx"),
  "quizId" : "xxx",
  "sessionId" : "xxx",
  "questionId" : "gender",
  "categoryId" : "1",
  "question" : "question 1",
  "answer" : "answer a",
  "created" : ISODate("2015-12-xxx"),
  "__v" : 0
}, // etc //

EDIT2:

预期产出:

{
  "_id" : {
    "quizId" : "xxx",
    "sessionId" : "xxx",
  },
  "sessionStarted" : "2015-12-xxx",
  "QuestionsSubmitted" : "2015-12-xxx"
  "answer" : {
    "0" : "answer a",
    "1" : "answer b"
    // etc //
  }
}

1 个答案:

答案 0 :(得分:-1)

有两个问题

1)

 sessionStarted: {$first: "$created"}

因为聚合具有管道阶段, 您的第一个created管道阶段中没有$group变量,因此首先添加创建的变量

2)

你的第二小组阶段是

{$group : { _id : {sessionId: "$sessionId", quizID: "$quizId" }, sessionStarted: {$first: "$created"}, QuestionsSubmitted: {$last: "$created"}, answer: {$push: "$answer"}}}

这里没有sessionId变量, 替换

$sessionId with $_id.sessionId 

$quizIdwith $_id.quizId

以下是您的回答,请尝试一下

db.questionanswers.aggregate( 
  [ 
    {$group : {_id : {sessionId: "$sessionId", quizID: "$quizId" }, answer: {$addToSet: "$answer"},sessionStarted: {$first: "$created"}, QuestionsSubmitted: {$last: "$created"} },
    {$unwind : "$answer"},
    {$sort : {answer: 1}},
    {$group : { _id : {sessionId: "$_id.sessionId", quizID: "$_id.quizId" }, sessionStarted: {$first: "$sessionStarted"}, QuestionsSubmitted: {$last: "$QuestionsSubmitted"}, answer: {$addToSet: "$answer"}}}
  ]
)

请试试这个