
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add Matched Key to List After Query in MongoDB
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 } ] }
Advertisements