How do I obtain the sum of a Loopback PersistedModel?
There does not seem to be a documentation on how to achieve that.
If possible I would like to avoid having to find all the rows and sum it in Node.js.
Trying out the example from https://github.com/strongloop/loopback/issues/890
var bookCollection = Book.getDataSource().connector.collection(Book.modelName);
I got an error
throw new Error('MongoDB connection is not established');
How do I get a handle on the collection to manually run aggregate query on a MongoDB collection?
On large collections of millions of documents, MongoDB's aggregation was shown to be much worse than Elasticsearch. Performance worsens with collection size when MongoDB starts using the disk due to limited system RAM. The $lookup stage used without indexes can be very slow.
As with many other database systems, MongoDB allows you to perform a variety of aggregation operations. These allow you to process data records in a variety of ways, such as grouping data, sorting data into a specific order, or restructuring returned documents, as well as filtering data as one might with a query.
In MongoDB, aggregation operations process the data records/documents and return computed results. It collects values from various documents and groups them together and then performs different types of operations on that grouped data like sum, average, minimum, maximum, etc to return a computed result.
The pipeline provides efficient data aggregation using native operations within MongoDB, and is the preferred method for data aggregation in MongoDB. The aggregation pipeline can operate on a sharded collection. The aggregation pipeline can use indexes to improve its performance during some of its stages.
Finally managed to get it working. Most examples left out the connect()
part.
My working code:
Book.getDataSource().connector.connect(function(err, db) {
var collection = db.collection('Book');
var author = Book.getDataSource().ObjectID(authorId);
collection.aggregate([
{ $match: { authorId: author } },
{ $group: {
_id: authorId,
total: { $sum: "$price" }
}}
], function(err, data) {
if (err) return callback(err);
return callback(null, data);
});
});
Aggregate query with loopback
Products.getDataSource().connector.connect(function(err, db) {
var collection = db.collection('Products');
collection.aggregate(
[{ $match: { "productCode" : "WIN10-NoOS" } }]
).toArray(function(err,servicesData){
if(err){
}else{
cb(null,servicesData);
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With