MongoDB count 命令

发布于

在MongoDB中,聚合命令计算集合或视图中的文档数量。count

它返回一个包含计数和命令状态的文档。

例

假设我们有一个包含以下文档的集合:pets

{ “_id” : 1, “name” : “Wag”, “type” : “Dog”, “weight” : 20 } { “_id” : 2, “name” : “Bark”, “type” : “Dog”, “weight” : 10 } { “_id” : 3, “name” : “Meow”, “type” : “Cat”, “weight” : 7 } { “_id” : 4, “name” : “Scratch”, “type” : “Cat”, “weight” : 8 } { “_id” : 5, “name” : “Bruce”, “type” : “Bat”, “weight” : 3 } { “_id” : 6, “name” : “Fetch”, “type” : “Dog”, “weight” : 17 } { “_id” : 7, “name” : “Jake”, “type” : “Dog”, “weight” : 30 }

我们可以使用以下查询来返回集合中的文档数:

db.runCommand( { count: "pets" } )

结果:

{ “n” : 7, “ok” : 1 }

MongoDB文档实际上建议不要在没有查询谓词的情况下使用该命令及其包装器方法。这是因为,在没有查询谓词的情况下运行时,它会根据集合的元数据返回结果,这可能会导致近似计数。count

计算查询结果

您可以使用以下窗体对查询结果进行计数。

例:

db.runCommand( { 
    count: "pets", 
    query: { type: "Dog" } 
} )

结果:

{ “n” : 4, “ok” : 1 }

在此示例中,我们可以看到集合中有四只狗。

让我们检查另一个查询的计数。这次我们将找出有多少宠物的体重超过一定数量。

db.runCommand( { count:'pets',
    query: { weight: { $gt: 10 } }
} )

结果:

{ “n” : 3, “ok” : 1 }

限制计数

您可以使用该参数指定要计数的最大文档数。limit

例:

db.runCommand( { 
    count: "pets", 
    query: { type: "Dog" },
    limit: 3
} )

结果:

{ “n” : 3, “ok” : 1 }

我们之前看到实际上有 4 只狗,但在这个例子中,我们将其限制为最多计数 3 只。

如果限制高于实际计数,则结果不会受到参数的影响。limit

例:

db.runCommand( { 
    count: "pets", 
    query: { type: "Dog" },
    limit: 10
} )

结果:

{ “n” : 4, “ok” : 1 }

跳过文档

您可以使用该参数在计数之前跳过多个文档。skip

例:

db.runCommand( { 
    count: "pets", 
    query: { type: "Dog" },
    skip: 2
} )

结果:

{ “n” : 2, “ok” : 1 }

折旧

请注意,MongoDB文档指出以下内容:

与 4.0 功能兼容的 MongoDB 驱动程序弃用了它们各自的游标和集合 API(运行命令),转而使用与 和 对应的新 API。有关给定驱动程序的特定 API 名称,请参阅驱动程序 API 文档。count()``count``countDocuments()``estimatedDocumentCount()

更多信息

该命令包括其他字段,如 、 和 。count``hint``comment``readConcern``collation

有关更多信息,请参阅 MongoDB 文档。