使用MongoDB C#驱动程序查询构建器获取项目计数 [英] Getting an item count with MongoDB C# driver query builder

查看:66
本文介绍了使用MongoDB C#驱动程序查询构建器获取项目计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用MongoDB的c#驱动程序,我可以轻松构造一个查询,然后针对该查询添加SetSkip()和SetLimit()参数,以将结果集限制为一定大小.

Using the c# driver for MongoDB I can easily construct a query against which I can then add SetSkip() and SetLimit() parameters to constrict the result set to a certain size.

但是,我希望能够在应用Skip and Take 而不执行查询并将整个结果集(可能很大)加载到其中之前,知道查询的项目数是多少记忆.

However I'd like to be able to know what item count of the query would be before applying Skip and Take without executing the query and loading the entire result set (which could be huge) into memory.

看起来我可以使用count()命令直接通过外壳对MongoDB进行此操作.例如:

It looks like I can do this with MongoDB directly through the shell by using the count() command. e.g.:

 db.item.find( { "FieldToMatch" : "ValueToMatch" } ).count()

这只是返回一个整数,而这正是我想要的.但是我在文档中看不到通过C#驱动程序执行此操作的方法.有可能吗?

Which just returns an integer and that's exactly what I want. But I can't see a way in the documentation of doing this through the C# driver. Is it possible?

(应该注意,我们已经在广泛使用查询构建器,因此,如果可能的话,理想情况下,我宁愿通过查询构建器来执行此操作,而不是开始通过驱动程序向外壳下发命令.但是如果那是唯一的解决方案,然后举个例子会很有帮助,谢谢.)

(It should be noted that we're already using the query builder extensively, so ideally I'd much rather do this through the query builder than start issuing commands down to the shell through the driver, if that's possible. But if that's the only solution then an example would be helpful, thanks.)

干杯, 马特

推荐答案

您可以这样做:

var server = MongoServer.Create("mongodb://localhost:27020");
var database = server.GetDatabase("someDb");

var collection = database.GetCollection<Type>("item");
var cursor = collection.Find(Query.EQ("FieldToMatch" : "ValueToMatch"));

var count = cursor.Count(); 

一些注意事项:

  1. 您应该只有一个服务器实例(单例)
  2. 最新驱动程序版本实际上返回的是长计数,而不是int
  3. 游标仅在迭代后才获取数据
  4. 您可以配置很多内容,例如跳过,获取,指定要在实际加载数据(开始迭代)之前在游标中返回的字段
  5. 光标的
  6. Count()方法仅加载文档计数

这篇关于使用MongoDB C#驱动程序查询构建器获取项目计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆