How can i make "Group By" query on loopback with mongodb connector ?
How can i make "Group By" query on loopback module with mongodb connector ? I can not find any document which say about that problem ? Please help me. Thanks
Are you meaning, is there a way to run MongoDB aggregations via loopback?
@jrschumacher : No, I'm using this way. It used collection of mongodb to make query on mongodb:
var bookCollection = Book.getDataSource().connector.collection(Book.modelName);
bookCollection.aggregate({
$group: {
_id: { category: "$category", author: "$author" },
total: { $sum: 1 }
}
}, function(err, groupByRecords) {
if(err) {
next(err);
} else {
next();
}
});
But i want a better solution, just use loopback lib but don't use mongodb collection directly.
@bluestaralone I looked at the source but there doesn't seem to be any reference to the aggregator. https://github.com/strongloop/loopback-connector-mongodb
@jrschumacher : Please see the codes:
- node_modules/loopback-connector-mongodb/node_modules/mongodb/lib/mongodb/collection.js Line 596: Collection.prototype.aggregate = function() { return aggregation.aggregate; }();
- node_modules/loopback-connector-mongodb/node_modules/mongodb/lib/mongodb/collection/aggregation.js Line: 253: var aggregate = function(pipeline, options, callback) {...
- node_modules/loopback-connector-mongodb/node_modules/mongodb/public/api/AggregationCursor.html Line 783: var cursor = collection.aggregate([... In this file you can see how to use it ?
Currently, i used "aggregate" method through loopback-connector-mongodb, but what do you think if we can use it through loopback Model ?
@raymondfeng @bajtos I don't know if thís problem is solved ?
aggregate is a mongodb query. Currently Loopback doesn't expose access to these queries.
edit: fix typo
@BerkeleyTrue :+1:
Sorry: meant to say 'doesn't...'
any update on this?
I don't think this is ever going to be first class. The way @bluestaralone laid out above is actually valid and the way I do things like this.
I am getting socket closed when use your example with async in parallel in a bit more complex method where i also query other models directly.
{ [MongoError: server XXXXX sockets closed]
name: 'MongoError',
message: 'server XXXXX sockets closed' }
It's not clear to me why this is labeled as a doc issue (and assigned to me). If I need to add something to the docs, please tell me what. If not, then I'm going to remove the "doc" label... and if it's not actionable, then I presume it should be closed @superkhau .
@crandmck Ask @bajtos, he added the doc + question label for this issue.
/cc @bajtos
I thought it would be a good idea to document how to make an aggregate (Group By) query in mongodb, using the solution described in https://github.com/strongloop/loopback/issues/890#issuecomment-66581628.
@crandmck if you think this does not belong to docs then I am fine with that too. In which case this GH issue can be closed right away.
OK, thanks, I see. I added https://docs.strongloop.com/display/LB/MongoDB+connector#MongoDBconnector-Aggregate(groupby)query It could probably use a bit more explanation, but I don't know anything about MongoDB, so suggestions welcome.
@crandmck thank you, the example LGTM. I'm closing this issue as done.
I would suggest to update doc since aggregate take other pipeline stages as an individual parameter.
bookCollection.aggregate( {
$match: {}
},
{
$group: {} }
... ,
function(err, groupByRecords) {
if(err) {
next(err);
} else {
next();
}
});
Thx @mike-aungsan, updated.
Why does the aggregation method take the stages of the pipeline as individual parameters? The mongo driver takes them as an array and it is convenient in the case you need to dynamically assemble the pipeline pushing/pulling stages in the array. Using individual parameters makes it less flexible IMHO.
I was trying to do something like this and came up with something that works, and I though I would contribute a more complete example, that would have saved me some time.
I have a model I want to do "group by" on. The model is in ./common/models/wafer.js. To that file, add:
Wafer.groupBy = function( filter, cb ) {
let waferCollection = Wafer.getDataSource().connector.collection( Wafer.modelName );
// OPTIONAL if ( ! filter.where ) return cb( new Error( 'missing a where clause in the filter' ) );
if ( ! filter.groupBy ) return cb( new Error( 'missing a groupBy clause in the filter' ) );
let pipeline = [];
if ( filter.where )
pipeline.push({ $match: filter.where });
pipeline.push({
$group: {
_id: '$' + filter.groupBy,
count: { $sum: 1 }
}
});
// rename the _id field to be the name of the groupBy field
let p = {
_id: 0,
count: 1
};
p[ filter.groupBy ] = "$_id";
pipeline.push({
$project: p
});
// console.log( 'pipeline:', JSON.stringify( pipeline, null, 2 ) );
waferCollection.aggregate( pipeline, cb );
}
Wafer.remoteMethod('groupBy', {
isStatic: true,
description: 'Invoke a group by',
accessType: 'WRITE',
accepts: {arg: 'filter', type: 'object', description: '{"where:{...}, "groupBy": "field"}'},
returns: {arg:'data', type:['object'], root:true}
});
You will now see a POST /api/wafers/groupBy endpoint in swagger. My wafer model has "product" and "lot" fields. You can input this filter to get the unique product names and the count for each:
{"groupBy": "product"}
The result will look like:
[
{
"count": 1926,
"product": "DB1681_UAD16"
},
{
"count": 8307,
"product": "B1681_UAD16"
}
]
Now, given a product, you can get the list of unique lot numbers and their counts:
{"where": {"product":"DB1681_UAD16"}, "groupBy":"lot"}
and the result:
[
{
"count": 16,
"lot": "6184410"
},
{
"count": 25,
"lot": "6184400"
},
(...)
]
One could probably generalize this further.
remember though this will only work when the datasource is MongoDB.