如何使用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