使用 MongoDB 压缩数组

rle*_*elr 4 mongodb mongodb-query aggregation-framework

是否可以在 mongo 文档中压缩数组?我指的是 zip 的函数式编程定义,其中相应的项被配对成元组。

更准确地说,我想从这样的 mongo 文档开始:

{
    "A" : ["A1", "A2", "A3"],
    "B" : ["B1", "B2", "B3"],
    "C" : [100.0, 200.0, 300.0]
}
Run Code Online (Sandbox Code Playgroud)

最终得到这样的 mongo 文档:

{"A":"A1","B":"B1","C":100.0},
{"A":"A2","B":"B2","C":200.0},
{"A":"A3","B":"B3","C":300.0},
Run Code Online (Sandbox Code Playgroud)

理想情况下,这将使用聚合框架,我已经使用该框架将我的文档带到此阶段。

sty*_*ane 5

从 MongoDB 3.4 开始,我们可以使用$zip运算符来压缩数组。

话虽如此,除非您知道数组的长度,否则我们无法获得预期的输出。

db.collection.aggregate( [ 
    { "$project": { 
        "zipped": { 
            "$zip": { "inputs": [ "$A", "$B", "$C" ] } 
        } 
    }}
])
Run Code Online (Sandbox Code Playgroud)

其产生:

{ 
    "_id" : ObjectId("578f35fb6db61a299a383c5b"),
    "zipped" : [
        [ "A1", "B1", 100 ],
        [ "A2", "B2", 200 ],
        [ "A3", "B3", 300 ]
    ]
}
Run Code Online (Sandbox Code Playgroud)

如果我们碰巧知道每个子数组中的元素数量,我们可以使用$map变量运算符返回子文档数组。

$map表达式中,我们需要使用$arrayElemAt运算符来设置字段 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 ] } 
                } 
            }
        }
    }}
] )
Run Code Online (Sandbox Code Playgroud)

其产生:

{
    "_id" : ObjectId("578f35fb6db61a299a383c5b"),
    "zipped" : [
        {
            "A" : "A1",
            "B" : "B1",
            "C" : 100
        },
        {
            "A" : "A2",
            "B" : "B2",
            "C" : 200
        },
        {
            "A" : "A3",
            "B" : "B3",
            "C" : 300
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)