Syntax error MongoDB query to add matched key to list after query?

MongoDB query to add matched key to list after query?



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 } ] }
Updated on: 2020-04-02T06:51:18+05:30

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements