I have a document that contains an array of arrays in my MongoDB collection.
{
"platformId":"CMC_123",
"carInfo":[
["Toyota",20,"White"],
["Suzuki",19,"Gray"],
["Ford",22,"Red"]
]
}
And I am expecting the below output
carMilage :{
"Toyota":20,
"Suzuki":19,
"Ford":22
}
My aggregation below
[
{
$match:{
platformId : "CMC_123"
}
},
{
$project:{
carMilage : '$carInfo'
}
}
]
I am stuck with the $project
field. How to achieve the above output using the $project
field. Thank you.
CodePudding user response:
$project
-2.1
$arrayToObject
- Convert array to object with result 2.1.1.2.1.1
$map
- IteratecarInfo
array. Get the first item ask
and the second item asv
for the current iterated array ($$this
).
db.collection.aggregate([
{
$match: {
platformId: "CMC_123"
}
},
{
$project: {
carMilage: {
"$arrayToObject": {
$map: {
input: "$carInfo",
in: {
k: {
$arrayElemAt: [
"$$this",
0
]
},
v: {
$arrayElemAt: [
"$$this",
1
]
}
}
}
}
}
}
}
])