如何计算 collection MongoDB Java 中的文档数?
How I can count documents in collection MongoDB Java?
我在 collection 中有很多文档
那么,我如何计算 collection
中的文档
获取集合的MongoCollection
或DBCollection
实例。例如:
MongoClient mongoClient = new MongoClient(
new ServerAddress("localhost", 27017));
DB db = mongoClient.getDB("mydb");
DBCollection collection = db.getCollection("test");
对集合对象调用 count()
方法。
显然,以上是针对 MongoDB 3.x 驱动程序 API。
如果您使用MongoDB 4.x API,您应该使用MongoCollection
接口提供的countDocuments()
方法。像这样。
MongoClient mongoClient = MongoClients.create(...);
MongoCollection collection = mongoClient.getCollection("test"); \
long count = collection.countDocuments();
(3.x API 现在被描述为“遗留”API。但是,我在 MongoDB 文档中看不到任何内容表明它们实际上已被弃用。如果有人能找到一些东西说明,请 post 下面的 URL。)
我在 collection 中有很多文档 那么,我如何计算 collection
中的文档获取集合的
MongoCollection
或DBCollection
实例。例如:MongoClient mongoClient = new MongoClient( new ServerAddress("localhost", 27017)); DB db = mongoClient.getDB("mydb"); DBCollection collection = db.getCollection("test");
对集合对象调用
count()
方法。
显然,以上是针对 MongoDB 3.x 驱动程序 API。
如果您使用MongoDB 4.x API,您应该使用MongoCollection
接口提供的countDocuments()
方法。像这样。
MongoClient mongoClient = MongoClients.create(...);
MongoCollection collection = mongoClient.getCollection("test"); \
long count = collection.countDocuments();
(3.x API 现在被描述为“遗留”API。但是,我在 MongoDB 文档中看不到任何内容表明它们实际上已被弃用。如果有人能找到一些东西说明,请 post 下面的 URL。)