从 MongoDB 3.4 开始,我们可以使用$zip运算符来压缩我们的数组。
话虽如此,除非您知道数组的长度,否则我们无法获得预期的输出。
db.collection.aggregate( [
{ "$project": {
"zipped": {
"$zip": { "inputs": [ "$A", "$B", "$C" ] }
}
}}
])
其产生:
{
"_id" : ObjectId("578f35fb6db61a299a383c5b"),
"zipped" : [
[ "A1", "B1", 100 ],
[ "A2", "B2", 200 ],
[ "A3", "B3", 300 ]
]
}
如果我们碰巧知道每个子数组中的元素数量,我们可以使用$map返回子文档数组的变量运算符。
In the $map
表达式,我们需要使用$arrayElemAt操作员到set我们的字段 A、B 和 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 ] }
}
}
}
}}
] )
其产生:
{
"_id" : ObjectId("578f35fb6db61a299a383c5b"),
"zipped" : [
{
"A" : "A1",
"B" : "B1",
"C" : 100
},
{
"A" : "A2",
"B" : "B2",
"C" : 200
},
{
"A" : "A3",
"B" : "B3",
"C" : 300
}
]
}