Does aggregation query with $match works in MongoDB?


Yes, it works in MongoDB. Let us create a collection with documents −

> db.demo358.insertOne({"ClientId":101,"ClientName":"Chris","ClientAge":34});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5692c0f8647eb59e5620cb")
}
> db.demo358.insertOne({"ClientId":102,"ClientName":"David","ClientAge":32});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5692caf8647eb59e5620cc")
}
> db.demo358.insertOne({"ClientId":103,"ClientName":"David","ClientAge":35});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5692d2f8647eb59e5620cd")
}
> db.demo358.insertOne({"ClientId":104,"ClientName":"Bob","ClientAge":31});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5692ddf8647eb59e5620ce")
}
> db.demo358.insertOne({"ClientId":105,"ClientName":"Chris","ClientAge":36});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5692e7f8647eb59e5620cf")
}

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

> db.demo358.find();

This will produce the following output −

{ "_id" : ObjectId("5e5692c0f8647eb59e5620cb"), "ClientId" : 101, "ClientName" : "Chris", "ClientAge" : 34 }
{ "_id" : ObjectId("5e5692caf8647eb59e5620cc"), "ClientId" : 102, "ClientName" : "David", "ClientAge" : 32 }
{ "_id" : ObjectId("5e5692d2f8647eb59e5620cd"), "ClientId" : 103, "ClientName" : "David", "ClientAge" : 35 }
{ "_id" : ObjectId("5e5692ddf8647eb59e5620ce"), "ClientId" : 104, "ClientName" : "Bob", "ClientAge" : 31 }
{ "_id" : ObjectId("5e5692e7f8647eb59e5620cf"), "ClientId" : 105, "ClientName" : "Chris", "ClientAge" : 36 }

Here is the how to work with $match in aggregate −

> db.demo358.aggregate(
...    [ { $match : { "ClientName" : "David" }},
...    { "$count": "ClientName" }
... ]
... );

This will produce the following output −

{ "ClientName" : 2 }

Updated on: 02-Apr-2020

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements