Fernando Gonzalez Fernando Gonzalez - 4 months ago 7
Node.js Question

Node.js "ignore" $sort in a collection.aggregate query



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?

Answer

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