使用mongo查询返回新的json结构

时间:2016-11-02 17:27:36

标签: json mongodb aggregation-framework

目前正在使用聚合过滤器来按sessionID对结果进行分组。是否可以在数据库中更改此内容:

 thread = new Thread(new connectTask());
 thread.start();

在MongoDb查询后返回:

{
  "_id" : ObjectId("xxx"),
  "quizId" : "xxx",
  "sessionId" : "xxx",
  "questionId" : "xxx",
  "categoryId" : "xxx",
  "question" : "text here",
  "answer" : "male",
  "created" : ISODate("2015-12-04T12:19:43.050Z"),
  "__v" : 0
},
{
  "_id" : ObjectId("xxx"),
  "quizId" : "xxx",
  "sessionId" : "xxx",
  "questionId" : "xxx",
  "categoryId" : "xxx",
  "question" : "another text here",
  "answer" : "25",
  "created" : ISODate("2015-12-04T12:19:43.050Z"),
  "__v" : 0
},
{
  "_id" : ObjectId("xxx"),
  "quizId" : "xxx",
  "sessionId" : "xxx",
  "questionId" : "xxx",
  "categoryId" : "xxx",
  "question" : "first question text here",
  "answer" : "answer A",
  "created" : ISODate("2015-12-04T12:19:43.050Z"),
  "__v" : 0
} // several questions more with same session ID//

1 个答案:

答案 0 :(得分:0)

感谢user3632894的帮助,我使用

按sessionID对答案进行了分组
db.questionanswers.aggregate( 
  [ 
    { $group : { _id : {sessionId: "$sessionId" }, answer: {$addToSet: "$answer"} } }
  ]
)

返回

{
  "sessionId" : "xxx",
  "answer" : [
    "0" : "answer A",
    "1" : "answer D",
    "2" : "answer C"
  ]
}