2015-02-03 9 views
9

Ho un documento che contiene una data e voglio raggruppare il documento in base al trimestre. Come posso farlo in MongoDB?
mio schema è:Come raggruppare la data trimestrale in MongoDB

var ekgsanswermodel = new mongoose.Schema({ 
    userId: {type: Schema.Types.ObjectId}, 
    topicId : {type: Schema.Types.ObjectId}, 
    ekgId : {type: Schema.Types.ObjectId}, 
    answerSubmitted :{type: Number}, 
    dateAttempted : { type: Date}, 
    title : {type: String}, 
    submissionSessionId : {type: String} 
}); 

1 ° trimestre contiene mesi 1, 2, 3. 2 ° trimestre contengono mesi 4, 5, 6 e così via fino a-4 ° trimestre. La mia risposta finale dovrebbe essere:

"result" : [ 
    { 
    _id: { 
     quater: 
    }, 
    _id: { 
     quater: 
    }, 
    _id: { 
     quater: 
    }, 
    _id: { 
     quater: 
    } 
    } 
+0

Hai provato a usare MapReduce di MongoDB? http://docs.mongodb.org/manual/core/map-reduce/ Penso che sia possibile mappare i mesi arrotondando MonthNumber/4. Qualcosa come emettere (this.number/4, this.number). E nella parte REDUCE, raggruppa tutti i mesi. – AzaFromKaza

+0

Non ho provato mapreduce. posso darmi un esempio ho aggiunto lo schema anche sopra. –

+0

Non importa la mia soluzione @grishabh, quella sotto è migliore. Mongodb mapreduce non ti permette di avere un array come risultato dell'operazione di riduzione. Riferimento: http://stackoverflow.com/questions/8175015/mongodb-mapreduce-reduce-multiple-not-supported-yet – AzaFromKaza

risposta

11

Si potrebbe fare uso dell'operatore $cond per controllare se:

  • Il $month è <= 3, progetto di un campo denominato quarter con valore come "uno".
  • Il $month è <= 6, progettare un campo denominato quarter con valore come "due".
  • Il $month è <= 9, progettare un campo denominato quarter con valore come "tre".
  • altrimenti il ​​valore del campo quarter sarebbe "quarto".
  • Quindi $group dal campo quarter.

Codice:

db.collection.aggregate([ 
{$project:{"date":1, 
      "quarter":{$cond:[{$lte:[{$month:"$date"},3]}, 
          "first", 
          {$cond:[{$lte:[{$month:"$date"},6]}, 
            "second", 
            {$cond:[{$lte:[{$month:"$date"},9]}, 
              "third", 
              "fourth"]}]}]}}}, 
{$group:{"_id":{"quarter":"$quarter"},"results":{$push:"$date"}}} 
]) 

specifico per lo schema:

db.collection.aggregate([ 
{$project:{"dateAttempted":1,"userId":1,"topicId":1,"ekgId":1,"title":1, 
      "quarter":{$cond:[{$lte:[{$month:"$dateAttempted"},3]}, 
          "first", 
          {$cond:[{$lte:[{$month:"$dateAttempted"},6]}, 
            "second", 
            {$cond:[{$lte:[{$month:"$dateAttempted"},9]}, 
              "third", 
              "fourth"]}]}]}}}, 
{$group:{"_id":{"quarter":"$quarter"},"results":{$push:"$$ROOT"}}} 
]) 
+1

thanx @BatScream, è possibile effettuare questa query in spring-data-mongodb. – user1503117

Problemi correlati