MongoDB cursor.size() 方法

在 MongoDB 中,cursor.size() 方法用于返回与查询匹配的文档数。

语法

db.collection.find().size()

该方法没有参数。

使用场景

在某些情况下,我们可能想要知道一个查询语句所匹配到的文档数量。例如,我们可能需要知道某个集合中有多少个文档与给定的查询条件匹配。在这种情况下,可以使用 cursor.size() 方法。

示例

下面是两个使用 cursor.size() 方法的示例:

假设我们有一个名为 employees 的集合,其中包含员工的记录。要获取所有部门为“Sales”的员工的数量,可以使用以下代码:

const cursor = db.employees.find({ department: "Sales" })
const count = cursor.size()
print(`Number of employees in Sales department: ${count}`)

输出结果:

Number of employees in Sales department: 42

假设我们有一个名为 orders 的集合,其中包含订单记录。要获取所有订单状态为“unprocessed”的数量,可以使用以下代码:

const cursor = db.orders.find({ status: "unprocessed" })
const count = cursor.size()
print(`Number of unprocessed orders: ${count}`)

输出结果:

Number of unprocessed orders: 18

结论

在 MongoDB 中,cursor.size() 方法可以返回与查询匹配的文档数。它可以用于获取与给定查询条件匹配的文档数量,这对于我们了解数据集合的规模和基本统计信息非常有用。