Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How do you convert an array of ObjectIds into an array of embedded documents with a field containing the original array element value?
To convert an array of ObjectIds into an array of embedded documents with a field containing the original array element value, use the $map operator within an aggregation pipeline. This transformation embeds each original array element as a value within a new document structure.
Syntax
db.collection.aggregate([
{
$addFields: {
arrayField: {
$map: {
input: "$arrayField",
in: { fieldName: "$$this" }
}
}
}
}
])
Sample Data
db.demo343.insertOne({
_id: 101,
UserName: "Chris",
details: [
{"Name": "John"},
{"Name": "David"}
]
});
{ "acknowledged": true, "insertedId": 101 }
Original Document Structure
db.demo343.find().pretty();
{
"_id": 101,
"UserName": "Chris",
"details": [
{
"Name": "John"
},
{
"Name": "David"
}
]
}
Example: Converting Array Elements
db.demo343.aggregate([
{
$addFields: {
details: {
$map: {
input: "$details",
in: { Name: "$$this" }
}
}
}
},
{ $out: "demo343" }
]);
Result After Conversion
db.demo343.find().pretty();
{
"_id": 101,
"UserName": "Chris",
"details": [
{
"Name": {
"Name": "John"
}
},
{
"Name": {
"Name": "David"
}
}
]
}
How It Works
-
$maptransforms each element in the input array -
$$thisrepresents the current array element being processed - Each original element becomes the value of the specified field in the new document structure
-
$outsaves the transformed documents back to the collection
Conclusion
Use $map with $$this to convert array elements into embedded documents. This technique preserves the original data while restructuring it into a nested format with each element as a field value.
Advertisements
