gpt4 book ai didi

mongodb - 使用 MongoDB 压缩数组

转载 作者:可可西里 更新时间:2023-11-01 09:43:23 26 4
gpt4 key购买 nike

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

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

{
"A" : ["A1", "A2", "A3"],
"B" : ["B1", "B2", "B3"],
"C" : [100.0, 200.0, 300.0]
}

最后得到像这样的 mongo 文档:

{"A":"A1","B":"B1","C":100.0},
{"A":"A2","B":"B2","C":200.0},
{"A":"A3","B":"B3","C":300.0},

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

最佳答案

从 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返回子文档数组的变量运算符。

$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 ] }
}
}
}
}}
] )

产生:

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

关于mongodb - 使用 MongoDB 压缩数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31164156/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com