How do I use MongoDB to count only collections that match two fields?



To count only collections that match two fields, use count(). Let us create a collection with documents −

> 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") }

Display all documents from a collection with the help of find() method −

> db.demo175.find();

This will produce the following output −

{ "_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" }

Following is the query to count only collections that match two fields −

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

This will produce the following output −

1
Updated on: 2020-03-27T06:52:51+05:30

120 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements