According to the mongodb node driver docs the aggregate function now returns a cursor (from 2.6).
I hoped that I could use this to get a count of items pre limit & skipping but there doesn't seem to be any count function on the created cursor. If I run the same queries in the mongo shell the cursor has an itcount function that I can call to get what I want.
I saw that the created cursor has an on data event (does that mean it's a CursorStream?) which seemed to get triggered the expected number of times, but if I use it in combination with cursor.get no results get passed into the callback function.
Can the new cursor feature be used to count an aggregation query?
Edit for code:
In mongo shell:
> db.SentMessages.find({Type : 'Foo'})
{ "_id" : ObjectId("53ea19af9834184ad6d3675a"), "Name" : "123", "Type" : "Foo" }
{ "_id" : ObjectId("53ea19dd9834184ad6d3675c"), "Name" : "789", "Type" : "Foo" }
{ "_id" : ObjectId("53ea19d29834184ad6d3675b"), "Name" : "456", "Type" : "Foo" }
> db.SentMessages.find({Type : 'Foo'}).count()
3
> db.SentMessages.find({Type : 'Foo'}).limit(1)
{ "_id" : ObjectId("53ea19af9834184ad6d3675a"), "Name" : "123", "Type" : "Foo" }
> db.SentMessages.find({Type : 'Foo'}).limit(1).count();
3
> db.SentMessages.aggregate([ { $match : { Type : 'Foo'}} ])
{ "_id" : ObjectId("53ea19af9834184ad6d3675a"), "Name" : "123", "Type" : "Foo" }
{ "_id" : ObjectId("53ea19dd9834184ad6d3675c"), "Name" : "789", "Type" : "Foo" }
{ "_id" : ObjectId("53ea19d29834184ad6d3675b"), "Name" : "456", "Type" : "Foo" }
> db.SentMessages.aggregate([ { $match : { Type : 'Foo'}} ]).count()
2014-08-12T14:47:12.488+0100 TypeError: Object #<Object> has no method 'count'
> db.SentMessages.aggregate([ { $match : { Type : 'Foo'}} ]).itcount()
3
> db.SentMessages.aggregate([ { $match : { Type : 'Foo'}}, {$limit : 1} ])
{ "_id" : ObjectId("53ea19af9834184ad6d3675a"), "Name" : "123", "Type" : "Foo" }
> db.SentMessages.aggregate([ { $match : { Type : 'Foo'}}, {$limit : 1} ]).itcount()
1
> exit
bye
In Node:
var cursor = collection.aggregate([ { $match : { Type : 'Foo'}}, {$limit : 1} ], { cursor : {}});
cursor.get(function(err, res){
// res is as expected (1 doc)
});
cursor.count() does not exist
cursor.itcount() does not exist
The on data event exists:
cursor.on('data', function(){
totalItems++;
});
but when used in combination with cursor.get, the .get callback function now contains 0 docs
Edit 2: The cursor returned appears to be an aggregation cursor rather than one of the cursors listed in the docs
count()
function defined on cursors not working? Note that the aggregation framework in the Node driver only returns a cursor when you set the cursor option. – Touchdown