javascript – How to fetch the highest date in MongoDB along with other parameters?

Question:

I have a schema that contains date, status and code:

var entregaSchema = mongoose.Schema({
        codEntrega: String,
        placaPipa: String,
        codRota: String,
        codMA: String,
        dataMA: Date,
        localMA: String,
        codPA: String,
        dataPA: Date,
        localPA: String,
        statusEntrega: String,
        cadEntrega: Date
});

I would like to sweep through this scheme and bring up the highest date for the past codPA with a 3 status that would be finalized.

Type: for codPA = 34 , where there is greater date and status = 3, this will be executed in a for for each PA , 1,2..34 and when found, it will perform another function of inserting a new delivery for this PA if one is time calculation in relation to the last date brought with a past time. Type, if dataPA >= 7 Insert delivery for this codPA .

Answer:

You can use mongodb's Aggregation framework to do this.

Using mongoose, it would look something like this:

// Troque essa linha pelo seu mapeamento
var entregaModel = mongoose.model("entrega", entregaSchema); 

entregaModel.aggregate([

    // Filtra para apenas os documentos com status = 3
    { $match: { statusEntrega: 3 }, 

    // Desses documentos, junte todos os que tem codPA iguais
    // E salve a maior dataPA em "maiorData"
    { $group: {
        _id: "$codPa",
        maiorData: { $max: "$dataPA"  }
    }}

], function (err, result) {
    if (err) 
        console.log(err);
    else
        // Sai a lista de todos os codPA e a data deles
        // já filtrados pelos com status = 3
        console.log(result);
});

To learn more about the aggregate framework of mongodb, read this link: https://docs.mongodb.com/manual/core/aggregation-pipeline/

The aggregate api in mongoose is at this link: http://mongoosejs.com/docs/api.html#aggregate_Aggregate

Hope this helps

Scroll to Top
AllEscort