Implement $match and $project in MongoDB aggregate

MongoDBDatabaseBig Data Analytics

The $match filters the documents to pass only the documents that match the specified condition to the next pipeline stage.

The $project passes along the documents with the requested fields to the next stage in the pipeline.

Let us see an example and create a collection with documents −

> db.demo545.insert({Name:"Chris",details:{SubjectScore1:56,SubjectScore2:56}})
WriteResult({ "nInserted" : 1 })
> db.demo545.insert({Name:"David",details:{SubjectScore1:78,SubjectScore2:78}})
WriteResult({ "nInserted" : 1 })

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

> db.demo545.find();

This will produce the following output −

{ "_id" : ObjectId("5e8e246e9e5f92834d7f05d5"), "Name" : "Chris", "details" : { "SubjectScore1" : 56, "SubjectScore2" : 56 } }
{ "_id" : ObjectId("5e8e24709e5f92834d7f05d6"), "Name" : "David", "details" : { "SubjectScore1" : 78, "SubjectScore2" : 78 } }

Following is the query to implement $match and $project −

>db.demo545.aggregate([{$match:{}},{$project:{"_id":0,"details.SubjectScore1":1,out:"$details
.SubjectScore2"}},{$group:{_id:"$out"}}])

This will produce the following output −

{ "_id" : 78 }
{ "_id" : 56 }
raja
Published on 14-May-2020 07:05:05
Advertisements