【发布时间】:2014-10-04 01:16:29
【问题描述】:
根据mongodb node driver docs,聚合函数现在返回一个游标(从 2.6 开始)。
我希望我可以使用它来获得预先限制和跳过的项目计数,但创建的光标上似乎没有任何计数功能。如果我在 mongo shell 中运行相同的查询,游标有一个 itcount 函数,我可以调用它来得到我想要的。
我看到创建的游标有一个 on data 事件(这是否意味着它是一个CursorStream?),它似乎被触发了预期的次数,但如果我将它与 cursor.get 结合使用,则没有结果传入回调函数。
新的游标功能可以用来统计聚合查询吗?
编辑代码:
在 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
在节点中:
var cursor = collection.aggregate([ { $match : { Type : 'Foo'}}, {$limit : 1} ], { cursor : {}});
cursor.get(function(err, res){
// res is as expected (1 doc)
});
cursor.count() 不存在
cursor.itcount() 不存在
on data 事件存在:
cursor.on('data', function(){
totalItems++;
});
但当与 cursor.get 结合使用时,.get 回调函数现在包含 0 个文档
编辑 2:返回的光标似乎是 aggregation cursor,而不是文档中列出的光标之一
【问题讨论】:
-
您能否向我们展示一些无法按预期工作的代码?在cursors 上定义的
count()函数是否不起作用?请注意,Node 驱动程序中的聚合框架只有在您设置游标选项时才会返回游标。 -
我在 mongo shell 中添加了一些代码示例(它可以按照我的方式工作)并使用 nodejs 驱动程序
-
我answered这个重复的问题,但Martijn Pieters指出is bad etiquette to answer duplicated questions,并继续删除我的答案,所以去这个链接:stackoverflow.com/a/60534958/218418我没有时间用于标记重复和该死的戏剧。
标签: javascript node.js mongodb mongodb-query