Aggregate data per month using Mongoose

Asked

Viewed 123 times

0

Hello! I need to aggregate data per month to use later to make charts. I am 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 calls per month, I was giving an olhdaa and what I did on 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 is correct but I had no mistake, but it also showed nothing. I thank anyone who can help me.

  • Then but your bank does not have the year, Month and day fields. There is no way you group like this, try to put the date field. Here are some examples

  • Oops, thanks for the reply! I already packed here and got the data the way I wanted, but thanks anyway

1 answer

1

I 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);
           });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.