Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
MongoDB query (aggregation framework) to match a specific field value
To match a specific field value, use a $match in MongoDB aggregation. Let us create a collection with documents −
> db.demo555.insertOne({"CountryName":"US"});{
"acknowledged" : true, "insertedId" : ObjectId("5e8f21bf54b4472ed3e8e85f")
}
> db.demo555.insertOne({"CountryName":"UK"});{
"acknowledged" : true, "insertedId" : ObjectId("5e8f21c254b4472ed3e8e860")
}
> db.demo555.insertOne({"CountryName":"US"});{
"acknowledged" : true, "insertedId" : ObjectId("5e8f21c354b4472ed3e8e861")
}
> db.demo555.insertOne({"CountryName":"AUS"});{
"acknowledged" : true, "insertedId" : ObjectId("5e8f21c554b4472ed3e8e862")
}
> db.demo555.insertOne({"CountryName":"US"});{
"acknowledged" : true, "insertedId" : ObjectId("5e8f21c754b4472ed3e8e863")
}
Display all documents from a collection with the help of find() method −
> db.demo555.find();
This will produce the following output: −
{ "_id" : ObjectId("5e8f21bf54b4472ed3e8e85f"), "CountryName" : "US" }
{ "_id" : ObjectId("5e8f21c254b4472ed3e8e860"), "CountryName" : "UK" }
{ "_id" : ObjectId("5e8f21c354b4472ed3e8e861"), "CountryName" : "US" }
{ "_id" : ObjectId("5e8f21c554b4472ed3e8e862"), "CountryName" : "AUS" }
{ "_id" : ObjectId("5e8f21c754b4472ed3e8e863"), "CountryName" : "US" }
Following is the query to match a specific field value −
> db.demo555.aggregate([
... {$match: {CountryName: 'US'}},
... {$group: {_id: null, Total: {$sum: 1}}}
... ])
This will produce the following output −
{ "_id" : null, "Total" : 3 } Advertisements
