MongoDB query to count records on the basis of matching criteria

MongoDBDatabaseBig Data Analytics

To count records on the basis of matching criteria, use count(). Let us create a collection with documents −

> db.demo205.insertOne(
...   {
...
...      "id": "101",
...      "Name": "",
...      "Age": "",
...      "isActive": false
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3d8a3003d395bdc21346eb")
}
> db.demo205.insertOne(
...   {
...
...      "id": "102",
...      "Name": "Chris",
...      "Age": "25",
...      "isActive": true
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3d8a3003d395bdc21346ec")
}
> db.demo205.insertOne(
...   {
...
...      "id": "103",
...      "Name": "",
...      "Age": "",
...      "isActive": false
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3d8a3003d395bdc21346ed")
}

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

> db.demo205.find();

This will produce the following output −

{ "_id" : ObjectId("5e3d8a3003d395bdc21346eb"), "id" : "101", "Name" : "", "Age" : "", "isActive" : false }
{ "_id" : ObjectId("5e3d8a3003d395bdc21346ec"), "id" : "102", "Name" : "Chris", "Age" : "25", "isActive" : true }
{ "_id" : ObjectId("5e3d8a3003d395bdc21346ed"), "id" : "103", "Name" : "", "Age" : "", "isActive" : false }

Following is the query to count records on the basis of matching criteria −

> db.demo205.count({
...   Name: "",
...   Age: "",
...   "isActive": false
... });

This will produce the following output −

2
raja
Published on 27-Mar-2020 10:41:54
Advertisements