How to search for the longest date in Mongodb along with other parameters?

Asked

Viewed 576 times

3

I have a schema 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’d like to sweep this scam and bring the biggest date to the codPA past and with status to 3 which would be finalised.

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

1 answer

1


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

Using Mongoosis, 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 mongodb Aggregate framework, read this link: https://docs.mongodb.com/manual/core/aggregation-pipeline/

The Aggregate api on Mongoose is on this link: http://mongoosejs.com/docs/api.html#aggregate_Aggregate

I hope I’ve helped

Browser other questions tagged

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