Vanaf MongoDB 3.4 kunnen we de $zip
operator om onze arrays te zippen.
Dat gezegd hebbende, kunnen we uw verwachte output niet krijgen tenzij u de lengte van uw array weet.
db.collection.aggregate( [
{ "$project": {
"zipped": {
"$zip": { "inputs": [ "$A", "$B", "$C" ] }
}
}}
])
die produceert:
{
"_id" : ObjectId("578f35fb6db61a299a383c5b"),
"zipped" : [
[ "A1", "B1", 100 ],
[ "A2", "B2", 200 ],
[ "A3", "B3", 300 ]
]
}
Als we het aantal elementen in elke subarray weten, kunnen we de $map
variabele operator die een array van subdocument retourneert.
In de $map
uitdrukking, moeten we de $arrayElemAt
gebruiken
operator om in te stellen de waarde van ons veld A, B en C.
db.collection.aggregate( [
{ "$project": {
"zipped": {
"$map": {
"input": {
"$zip": { "inputs": [ "$A", "$B", "$C" ] }
},
"as": "el",
"in": {
"A": { "$arrayElemAt": [ "$$el", 0 ] },
"B": { "$arrayElemAt": [ "$$el", 1 ] },
"C": { "$arrayElemAt": [ "$$el", 2 ] }
}
}
}
}}
] )
die produceert:
{
"_id" : ObjectId("578f35fb6db61a299a383c5b"),
"zipped" : [
{
"A" : "A1",
"B" : "B1",
"C" : 100
},
{
"A" : "A2",
"B" : "B2",
"C" : 200
},
{
"A" : "A3",
"B" : "B3",
"C" : 300
}
]
}