Monday, 17 April 2017

MongoDB mongoose aggregation / math operations

Hya!

I'm just studying MongoDB and have a problem with understanding of how exactly $aggregation method works in Mongoose (nodejs driver) in mongo. To be honest, I couldn't found any code examples in mongoose docs (I haven't found even [search] option on their site [google site:mongoosejs.com helps me])

So, I hope someone will helps me to explain this and answer my question.

For example I have have a various documents in my collection, with fields:

{ "_id":001, "item":47139, "total_price": 560000, "quantity": 56, "lastModified" : 1491748073000 }
{ "_id":001, "item":xxxxx, "total_price": yyyyy, "quantity": zz, "lastModified" : 1491748073000 }
{ "_id":001, "item":47139, "total_price": 1750000, "quantity": 150, "lastModified" : 1491748073000 }

and I would like to $summ all the "quantity" for documents with id: 47139 and timestamp: 1491748073000. As for now this code (JS) works fine and provides to me a necessary data:

var server = mongoose.model('Name_of_my_Schema',Schema);

server.find({ lastModified : 1491748073000, item : 47139 }, null, {sort: 'buyout'},function (err, res) {
    total = 0;
    for (i = 0; i < res.length; i++) {  //sorry, map.reduce, but not this time
        total += res[i].quantity; 
    }
    console.log(total);
});

but is it possible to do this operation via mongoose? According to mongo docs I should use this code for matching the necessary array of docs, like these:

server.aggregate().match({
    lastModified : 1491748073000,
    item : 47139
    }).exec(function (err, result){
    console.log(result);
    console.log(err);
});

and then use $group to group necessary data and { $sum: "quantity" }, but what I should do next? Why should I use $group, if I just want to receive summ of all quantity? Could someone give me a clue what am I missing?



via AlexZeDim

No comments:

Post a Comment