要计算文档数,请在MongoDB中使用count()。让我们创建一个包含文档的集合-
> db.demo664.insertOne({_id:1,ClientName:"Chris"}); { "acknowledged" : true, "insertedId" : 1 } > db.demo664.insertOne({_id:2,ClientName:"Bob"}); { "acknowledged" : true, "insertedId" : 2 } > db.demo664.insertOne({_id:3,ClientName:"Sam"}); { "acknowledged" : true, "insertedId" : 3 } > db.demo664.insertOne({_id:4,ClientName:"David"}); { "acknowledged" : true, "insertedId" : 4 }
在find()方法的帮助下显示集合中的所有文档-
> db.demo664.find();
这将产生以下输出-
{ "_id" : 1, "ClientName" : "Chris" } { "_id" : 2, "ClientName" : "Bob" } { "_id" : 3, "ClientName" : "Sam" } { "_id" : 4, "ClientName" : "David" }
以下是计算行数的查询-
> var numberOfRows=db.demo664.count(); > print ("Number Of Rows="+numberOfRows);
这将产生以下输出-
Number Of Rows=4