- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to convert an array to a map of documents with n attributes?
For this, you can use $map. Let us first create a collection with documents −
> db.demo398.insertOne({ ... "details":[ ... { ... "Name":"Chris", ... "Age":22 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5e8cedfac4d418a017856c") }
Display all documents from a collection with the help of find() method −
> db.demo398.find();
This will produce the following output −
{ "_id" : ObjectId("5e5e8cedfac4d418a017856c"), "details" : [ { "Name" : "Chris", "Age" : 22 } ] }
Following is the query to convert an array to a map of documents with n attributes −
> db.demo398.aggregate([ ... { ... "$addFields": { ... "details": { ... "$arrayToObject": { ... "$map": { ... "input": "$details", ... "as": "out", ... "in": { ... "k": "$$out.Name", ... "v": "$$out" ... } ... } ... } ... } ... } ... } ... ])
This will produce the following output −
{ "_id" : ObjectId("5e5e8cedfac4d418a017856c"), "details" : { "Chris" : { "Name" : "Chris", "Age" : 22 } } }
Advertisements