- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How do you convert an array of ObjectIds into an array of embedded documents with a field containing the original array element value?
For such conversion, use aggregate. Let us create a collection with documents −
> db.demo343.insertOne({ ... _id: 101, ... UserName: "Chris", ... details: [ ... {"Name":"John"}, ... {"Name":"David"} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method −
> db.demo343.find().pretty();
This will produce the following output −
{ "_id" : 101, "UserName" : "Chris", "details" : [ { "Name" : "John" }, { "Name" : "David" } ] }
Following is the query to convert an array of objects into an array of embedded documents with a field containing the original array element value −
> db.demo343.aggregate([ ... { ... $addFields: { ... details: { ... $map: { ... input: "$details", ... in: { Name: "$$this" } ... } ... } ... } ... }, ... { $out: "demo343" } ... ])
Display all documents from a collection with the help of find() method −
> db.demo343.find().pretty();
This will produce the following output −
{ "_id" : 101, "UserName" : "Chris", "details" : [ { "Name" : { "Name" : "John" } }, { "Name" : { "Name" : "David" } } ] }
- Related Articles
- How do you convert a list collection into an array in C#?
- How to move an array of embedded documents up to parent and change key/value with aggregation pipeline?
- Query an array of embedded documents in MongoDB and push another?
- MongoDB aggregate to convert multiple documents into single document with an array?
- Convert an array of datetimes into an array of strings in Python
- Convert an array of datetimes into an array of strings with UTC timezone in Python
- Increment value of an array element with array object in MongoDB
- How do you convert an ArrayList to an array in Java?
- How to convert an array into a complex array JavaScript?
- Convert an array of datetimes into an array of strings with pytz timezone object in Python
- How can I count the documents in an array based on the value of a specific field?
- Replace an array field value with MongoDB?
- Add a field to an embedded document in an array in MongoDB?
- How do you limit an array sub-element in MongoDB?
- Convert an array of datetimes into an array of strings passing units in Python

Advertisements