0


This could be a dumb question, but I'm desperate already! I need to do this query:

db.clients.aggregate(
{
  $group: {
      _id: '$enterprise',
      lodging_days: { $sum: '$lodging_days' }
  }
},
{
  $sort : {
    lodging_days: -1
  }
})

And, if I copy this on the mongo bash, I returned this: Bash Return (Sorry, I can't upload images yet)
JUST LIKE I WANT!

But, when I put the query on node:

router.get('/query', function(req, res){
  var db = req.db;
  var clients=db.get('clients');

  clients.aggregate(
    {
      $group: {
        _id: '$enterprise',
        lodging_days: { $sum: '$lodging_days' }
      }
    },
    {
      $sort: {
        'lodging_days': -1
      }
    },
    function(e, data){
      res.json(data);
    }
  );
});

This "ignore" the $sort and return me this: Interface Return
Now, my question are... Why!? And what can I make to fix it?

4
  • Try to wrap your pipeline into array. db.collection.aggregate( [ { <stage> }, ... ] ) Commented Jul 21, 2016 at 14:56
  • The way you call aggregate does not soom to match how the API says you should be calling it. mongodb.github.io/node-mongodb-native/2.2/api/… Commented Jul 21, 2016 at 14:58
  • From your link: // Execute aggregate, notice the pipeline is expressed as an Array collection.aggregate([]) I mean you need to do next clients.aggregate([your code with group, sort and function]); Commented Jul 21, 2016 at 15:00
  • @VladislavKievski Oh!! That's the way! It's work! Thanks! Plz Post this like an answer, so I can validate it. Commented Jul 21, 2016 at 15:03

1 Answer 1

1

Your need to wrap your pipeline into array.

router.get('/query', function(req, res){
  var db = req.db;
  var clients=db.get('clients');

  clients.aggregate([
    {
      $group: {
        _id: '$enterprise',
        lodging_days: { $sum: '$lodging_days' }
      }
    },
    {
      $sort: {
        'lodging_days': -1
      }
    }],
    function(e, data){
      res.json(data);
    }
  );
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It need to wrap only the aggregate commands, the function goes outside. router.get('/query', function(req, res){ var db = req.db; var clients=db.get('clients'); clients.aggregate([ { $group: { _id: '$enterprise', lodging_days: { $sum: '$lodging_days' } } }, { $sort: { 'lodging_days': -1 } }], function(e, data){ res.json(data); } ); });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.