Mongoose Document Model.countDocuments()函数
Mongoose API的Model.countDocuments()方法用于计算集合中存在的文档数量。countDocuments()方法根据匹配的过滤条件计算集合中的文档数量。
Model.countDocuments()方法接受四个参数:
- filter: 这是一个对象,用于过滤需要更新的文档。
- callback: 这是一个回调函数,一旦执行完成就会运行。
返回类型: Model.create()函数返回一个promise。
设置Node.js应用程序:
步骤1: 使用以下命令创建一个Node.js应用程序:
npm init
步骤2: 创建NodeJS应用之后,使用以下命令安装所需模块:
npm install mongoose
项目结构:
项目结构将如下所示:
数据库结构: 数据库结构将如下所示,以下文档存在集合中。
示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接并定义了customerSchema模型,模型包含两个列“name”和“orderCount”。最后,我们使用countDocuments()方法来获取“orderCount”值为10的文档在集合中的数量。
- app.js: 将以下代码写入app.js文件中:
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
mongoose.connect(
"mongodb://localhost:27017/geeksforgeeks", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Defining customerSchema schema
const customerSchema = new mongoose.Schema({
name: String,
orderCount: Number,
});
// Defining customerSchema model
const Customer = mongoose.model("Customer", customerSchema);
// Calling countDocuments() on Customer model
Customer.countDocuments({ orderCount: 10 },
function (err, count) {
console.log("there are %d documents with orderCount
value as 10", count);
});
运行程序的步骤: 从项目的根目录执行以下命令来运行应用程序:
node app.js
输出:
控制台输出:
there are 3 documents with orderCount value as 10
您可以使用任何GUI工具以图形形式表示数据库。在这里,我使用了Robo3T GUI工具进行图形表示。
示例2: 在这个示例中,我们使用mongoose建立了一个数据库连接,并定义了customerSchema模型,拥有两列 “name” 和 “orderCount”。最后,我们使用countDocuments()方法来获取集合中”name”为”Rahul”的文档数量。
- app.js: 在app.js文件中写入以下代码:
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Defining customerSchema schema
const customerSchema = new mongoose.Schema({
name: String,
orderCount: Number,
});
// Defining customerSchema model
const Customer = mongoose.model(
"Customer", customerSchema);
Customer.countDocuments({ name: "Rahul" },
function (err, count) {
console.log("there are %d documents
with name value as Rahul", count);
});
运行程序的步骤: 要运行应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
在控制台中:
there are 1 documents with name value as Rahul
你可以使用任何GUI工具以图形形式表示数据库。在这里,我使用了Robo3T GUI工具进行图形表示。
参考: https://mongoosejs.com/docs/api/model.html#model_Model-countDocuments