loopback icon indicating copy to clipboard operation
loopback copied to clipboard

How can i make "Group By" query on loopback with mongodb connector ?

Open bluestaralone opened this issue 12 years ago • 37 comments

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

bluestaralone avatar Dec 03 '14 03:12 bluestaralone

Are you meaning, is there a way to run MongoDB aggregations via loopback?

jrschumacher avatar Dec 11 '14 06:12 jrschumacher

@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 avatar Dec 11 '14 07:12 bluestaralone

@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 avatar Dec 11 '14 12:12 jrschumacher

@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 ?

bluestaralone avatar Dec 12 '14 02:12 bluestaralone

@raymondfeng @bajtos I don't know if thís problem is solved ?

bluestaralone avatar Feb 10 '15 08:02 bluestaralone

aggregate is a mongodb query. Currently Loopback doesn't expose access to these queries.

edit: fix typo

BerkeleyTrue avatar Jun 03 '15 22:06 BerkeleyTrue

@BerkeleyTrue :+1:

bluestaralone avatar Jun 04 '15 02:06 bluestaralone

Sorry: meant to say 'doesn't...'

BerkeleyTrue avatar Jun 04 '15 03:06 BerkeleyTrue

any update on this?

eterna2 avatar Jul 08 '15 10:07 eterna2

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.

BerkeleyTrue avatar Jul 08 '15 14:07 BerkeleyTrue

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' }

kussberg avatar Nov 05 '15 11:11 kussberg

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 avatar Nov 05 '15 19:11 crandmck

@crandmck Ask @bajtos, he added the doc + question label for this issue.

/cc @bajtos

superkhau avatar Nov 06 '15 08:11 superkhau

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.

bajtos avatar Nov 09 '15 10:11 bajtos

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 avatar Nov 10 '15 23:11 crandmck

@crandmck thank you, the example LGTM. I'm closing this issue as done.

bajtos avatar Nov 16 '15 15:11 bajtos

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

mike-aungsan avatar Dec 24 '15 00:12 mike-aungsan

Thx @mike-aungsan, updated.

crandmck avatar Dec 28 '15 18:12 crandmck

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.

virgafox avatar Jan 06 '16 11:01 virgafox

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.

peebles avatar Jun 02 '17 19:06 peebles