MongoDB aggregation on Loopback

和自甴很熟 提交于 2019-12-29 05:30:24

问题


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.

UPDATE

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?


回答1:


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



回答2:


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

         });
    });


来源:https://stackoverflow.com/questions/30673606/mongodb-aggregation-on-loopback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!