Search code examples
node.jsmongodbprojection

Mongo DB differences in NodeJS query result


With executing following query in MongoDB (3.2.7) shell:

db.coll.aggregate({$group: {_id : '$Name', count : {$sum: 1 }}}, {$project: { _id:0, Name: '$_id', count: 1 }})

I got exactly what I need:

{ "count" : 4, "Name" : "Name1" }
{ "count" : 5, "Name" : "Name2" }
{ "count" : 1, "Name" : "Name3" }
{ "count" : 9, "Name" : "Name4" }

I want to use this aggregation in NodeJS (mongodb node module 2.2.5) so I define an API:

app.get('/api', function(req, res){
        db.collection('coll').aggregate({$group: {_id : '$Name', count : {$sum: 1 }}}, {$project: { _id: 0, Name: '$_id', count: 1 }}).toArray(function(err, docs) {
            if (err) {
                assert.equal(null);
            }
            else {
                console.log(docs);
                res.json(docs);
            }
        });
    });

When I execute this API, I got different result in regards to the shell result:

[{"_id":"Name1","count":4},{"_id":"Name2","count":5},{"_id":"Name3","count":1},{"_id":"Name4","count":9}]

Does anyone know why is so that? It seems that $project function didn't executed in NodeJS API.


Solution

  • The documentation states that the pipeline (first argument to aggregate) should be an array:

    db.collection('coll').aggregate([{
      $project: { _id: 0, Name: '$_id', count: 1 }
    }, {
      $group: {_id : '$Name', count : { $sum: 1 } }
    }]).toArray(...)