如何使用 MongoDB 仅计算匹配两个字段的集合?


要仅计算匹配两个字段的集合,请使用 count()。我们创建一个包含文档的集合 -

> db.demo175.insertOne({"EmployeeName":"Bob","isMarried":"YES"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3840969e4f06af551997e8")
}
> db.demo175.insertOne({"EmployeeName":"David","isMarried":"NO"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e38409e9e4f06af551997e9")
}
> db.demo175.insertOne({"EmployeeName":"Mike","isMarried":"YES"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3840a79e4f06af551997ea")
}
> db.demo175.insertOne({"EmployeeName":"Sam","isMarried":"NO"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3840ae9e4f06af551997eb")
}

在集合中显示所有文档,借助 find() 方法 -

> db.demo175.find();

这将产生以下输出 -

{ "_id" : ObjectId("5e3840969e4f06af551997e8"), "EmployeeName" : "Bob", "isMarried" : "YES" }
{ "_id" : ObjectId("5e38409e9e4f06af551997e9"), "EmployeeName" : "David", "isMarried" : "NO" }
{ "_id" : ObjectId("5e3840a79e4f06af551997ea"), "EmployeeName" : "Mike", "isMarried" : "YES" }
{ "_id" : ObjectId("5e3840ae9e4f06af551997eb"), "EmployeeName" : "Sam", "isMarried" : "NO" }

以下是仅计算匹配两个字段的集合的查询 -

> db.demo175.count( { "EmployeeName": "Mike", "isMarried":"YES" } );

这将产生以下输出 -

1

更新日期:2020-03-27

90 次浏览

启动你的 职业生涯

完成课程进行认证

开始吧
广告