本文介绍了环回上的MongoDB聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取Loopback PersistedModel的总和?
How do I obtain the sum of a Loopback PersistedModel?
关于如何实现该目标,似乎没有文档.
There does not seem to be a documentation on how to achieve that.
如果可能的话,我希望避免查找所有行并将其汇总到Node.js中.
If possible I would like to avoid having to find all the rows and sum it in Node.js.
从 https://github.com/strongloop/loopback/issues/890中尝试示例
var bookCollection = Book.getDataSource().connector.collection(Book.modelName);
我遇到了错误
throw new Error('MongoDB connection is not established');
如何获取集合的句柄以在MongoDB集合上手动运行聚合查询?
How do I get a handle on the collection to manually run aggregate query on a MongoDB collection?
推荐答案
最终设法使其正常运行.大多数示例都省略了connect()
部分.
Finally managed to get it working. Most examples left out the connect()
part.
我的工作代码:
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);
});
});
这篇关于环回上的MongoDB聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!