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
MongoDB query to convert an array to a map of documents with n attributes?
To convert an array to a map of documents with n attributes in MongoDB, use the $arrayToObject operator combined with $map. This transforms array elements into key-value pairs where each document becomes a property of the resulting object.
Syntax
db.collection.aggregate([
{
"$addFields": {
"fieldName": {
"$arrayToObject": {
"$map": {
"input": "$arrayField",
"as": "item",
"in": {
"k": "$$item.keyField",
"v": "$$item"
}
}
}
}
}
}
])
Sample Data
db.demo398.insertOne({
"details": [
{
"Name": "Chris",
"Age": 22
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e5e8cedfac4d418a017856c")
}
Example
Display the original document structure ?
db.demo398.find();
{ "_id": ObjectId("5e5e8cedfac4d418a017856c"), "details": [ { "Name": "Chris", "Age": 22 } ] }
Convert the array to a map using the Name field as the key ?
db.demo398.aggregate([
{
"$addFields": {
"details": {
"$arrayToObject": {
"$map": {
"input": "$details",
"as": "out",
"in": {
"k": "$$out.Name",
"v": "$$out"
}
}
}
}
}
}
])
{ "_id": ObjectId("5e5e8cedfac4d418a017856c"), "details": { "Chris": { "Name": "Chris", "Age": 22 } } }
How It Works
-
$mapiterates through each array element -
kdefines the key (using Name field value) -
vdefines the value (the entire document) -
$arrayToObjectconverts the key-value pairs into an object
Conclusion
The $arrayToObject and $map combination effectively transforms arrays into objects, making it easier to access documents by their attribute values as keys rather than array indices.
Advertisements
