Mongoose Query.prototype.estimatedDocumentCount()函数
estimatedDocumentCount() 方法是Mongoose Query API的一部分,用于估计集合中文档的数量。它使用元数据提供了近似文档计数,速度比计算集合中所有文档要快。
语法:
const MyModel = mongoose.model('MyModel', mySchema);
MyModel.estimatedDocumentCount()
.then((count) => {
...
})
.catch((err) => {
console.error(err);
});
安装mongoose模块:
步骤1: 您可以使用以下命令安装此软件包。
npm install mongoose
步骤2: 在安装mongoose模块之后,您可以在命令提示符中使用命令检查您的mongoose版本。
npm version mongoose
步骤3: 之后,您只需创建一个文件夹并添加一个文件,例如index.js,要运行此文件,您需要运行以下命令。
node index.js
项目结构: 项目的结构将如下所示:

示例1: 在此示例中,使用estimatedDocumentCount()函数来获取shopDB集合中产品文档的大致数量。Product模型定义了一个包含四个字段的架构:id、name、price和stock。调用estimatedDocumentCount()方法来获取文档的近似计数,并将其记录在控制台中。
- Index.js
const mongoose = require("mongoose");
mongoose.set("strictQuery", true);
mongoose
.connect("mongodb://localhost:27017/shopDB")
.then(() => {
const products = mongoose.model("Products", {
id: Number,
name: String,
price: Number,
stock: Number,
});
products
.estimatedDocumentCount()
.then((count) => {
console.log(
`There are approximately ${count} products in the collection.`
);
mongoose.connection.close();
})
.catch((err) => console.error(err));
})
.catch((err) => console.error(err));
//Code contributed by Anurag Sharma
运行应用程序的步骤: 通过以下命令运行index.js文件:
步骤1: 确保你已经安装了mongoose模块,使用以下命令:
npm install mongoose
步骤2: 在执行该函数之前,数据库中的示范数据如下所示,您可以使用任何GUI工具或终端来查看数据库,就像我们使用 MongoDB compass GUI 工具一样,如下所示:

步骤3: 使用以下命令运行index.js文件:
node index.js
输出:

示例2:
在这个示例中,estimatedDocumentCount()用于获取cseSociety集合中User文档的近似数量。
const mongoose = require("mongoose");
mongoose.set("strictQuery", true);
mongoose
.connect("mongodb://localhost:27017/cseSociety")
.then(() => {
const users = mongoose.model("Users", {
fullName: String,
userName: String,
email: String,
phone: Number,
});
users
.estimatedDocumentCount()
.then((count) => {
console.log(
`There are approximately ${count} users in the collection.`
);
mongoose.connection.close();
})
.catch((err) => console.error(err));
})
.catch((err) => console.error(err));
//Code contributed by Anurag Sharma
运行应用程序的步骤:
使用以下命令运行index.js文件:
步骤1:
在此示例中,我们使用以下文档:

步骤2: 使用以下命令运行index.js文件:
node index.js
结果:

参考:https://mongoosejs.com/docs/api/model.html#model_Model.estimatedDocumentCount
极客教程