MongoDB query to add matched key to list after query?

MongoDBDatabaseBig Data Analytics

For this, use aggregate() in MongoDB. Let us create a collection with documents −

> db.demo334.insertOne({
...    "Name": "Chris",
...    "Age": 21,
...    "details": [{
...       "Subject": "MySQL",
...       "Score": 78
...    }, {
...       "Subject": "MongoDB",
...       "Score": 45
...    }]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e52241bf8647eb59e562090")
}

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

> db.demo334.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e52241bf8647eb59e562090"),
   "Name" : "Chris",
   "Age" : 21,
   "details" : [
      {
         "Subject" : "MySQL",
         "Score" : 78
      },
      {
         "Subject" : "MongoDB",
         "Score" : 45
      }
   ]
}

Following is the query to add matched key to list after query −

> db.demo334.aggregate([
...    { $addFields: {
...       details: {$filter: {
...          input: '$details',
...          as: 'out',
...          cond: {$gte: ['$$out.Score',70 ]}
...       }}
...    }}
... ])

This will produce the following output −

{ "_id" : ObjectId("5e52241bf8647eb59e562090"), "Name" : "Chris", "Age" : 21, "details" : [ { "Subject" : "MySQL", "Score" : 78 } ] }
raja
Published on 02-Apr-2020 06:50:33
Advertisements