MongoDB 中 count() 和 find().count() 的区别是什么?
count() 和 find().count() 没有区别。让我们看看它们是如何工作的。为了理解这个概念,让我们用文档创建一个集合。创建带有文档的集合的查询如下 −
> db.countDemo.insertOne({"UserId":1,"UserName":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7f9d278d10a061296a3c5d")
}
> db.countDemo.insertOne({"UserId":2,"UserName":"Carol"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7f9d308d10a061296a3c5e")
}
> db.countDemo.insertOne({"UserId":3,"UserName":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7f9d3a8d10a061296a3c5f")
}
> db.countDemo.insertOne({"UserId":4,"UserName":"Mike"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7f9d428d10a061296a3c60")
}使用 find() 方法显示集合中的所有文档。查询如下 −
> db.countDemo.find().pretty();
输出如下 −
{
"_id" : ObjectId("5c7f9d278d10a061296a3c5d"),
"UserId" : 1,
"UserName" : "John"
}
{
"_id" : ObjectId("5c7f9d308d10a061296a3c5e"),
"UserId" : 2,
"UserName" : "Carol"
}
{
"_id" : ObjectId("5c7f9d3a8d10a061296a3c5f"),
"UserId" : 3,
"UserName" : "Bob"
}
{
"_id" : ObjectId("5c7f9d428d10a061296a3c60"),
"UserId" : 4,
"UserName" : "Mike"
}以下是用于统计记录数的 count() 查询 −
> db.countDemo.count();
输出如下 −
4
以下是用于 count().find() 的查询。查询如下 −
> db.countDemo.find().count();
输出如下 −
4
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP