以下是计算MongoDB集合中文档数的语法
let anyVariableName= db.getCollection(‘yourCollectionName’); yourVariableName.count();
首先让我们创建一个包含文档的集合
> db.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9a5e2015e86fd1496b38a1") } >db.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Ramit","CustomerAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c9a5e3515e86fd1496b38a2") } >db.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Adam","CustomerAge":27,"CustomerCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9a5e4c15e86fd1496b38a3") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.countNumberOfDocumentsDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9a5e2015e86fd1496b38a1"), "CustomerName" : "Bob" } { "_id" : ObjectId("5c9a5e3515e86fd1496b38a2"), "CustomerName" : "Ramit", "CustomerAge" : 23 } { "_id" : ObjectId("5c9a5e4c15e86fd1496b38a3"), "CustomerName" : "Adam", "CustomerAge" : 27, "CustomerCountryName" : "US" }
以下是查询以计算MongoDB集合中的文档数的查询,
> let myCollectionName = db.getCollection('countNumberOfDocumentsDemo'); > myCollectionName.count();
这将产生以下输出
3