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
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"
}
}
]
}Advertisements