Add data per month using mongoose

0

Hello! I need to aggregate data per month to use later to make charts. I'm using Mongoose as ODM and the following scheme:

module.exports = mongoose.model('atendimento', {
    id: String,
    id_atendimento: { type: Number, default: 0 },
    id_cliente: { type: Number, default: 0 },
    id_user: mongoose.Schema.Types.ObjectId,
    user_nome: String,
    cliente_nome: String,
    id_atendente: { type: Number, default: 0 },
    atendente_nome: String,
    atendente_imagem: String,
    setor: Number,
    descricao: String,
    status: String,
    date: { type: Date, default: Date.now },
    inicio: { type: Date, default: Date.now },
    fim: { type: Date, default: Date.now },
    update: { type: Date, default: Date.now }
});

I need all the appointments per month, I was giving a look and what I did in the route that will have the data was as follows:

     atendimentos.aggregate({
       $group: {
         _id: {
             year: {$year: "$date"},
             month: {$month: "$date"},
             day: {$dayOfMonth: "$date"}

         },
         total: {$sum: 1}
       }

    });

I do not know if it's correct but I did not have any errors, but it also did not show anything. Thank you for helping me.

    
asked by anonymous 06.08.2018 / 18:55

1 answer

1

I have decided as follows:

collection.aggregate([
               { $project:
                       { _id: "$month",
                         year: {$year: "$date" },
                           month: { $month: "$date"},
                           amount: 1
                       }
               },
               { $group:
                       { _id: { year: "$year", month: ("$month")},
                           sum: { $sum: 1}
                       }
           }]).exec(function(error, items){
                if(error){return next(error);}

                console.log(items);
           });
    
06.08.2018 / 22:33