使用 MongoDB 压缩数组 [英] Zip arrays with MongoDB

查看:14
本文介绍了使用 MongoDB 压缩数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to zip arrays within a mongo document? I mean the functional programming definition of zip, where corresponding items are paired into tuples.

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

To be more precise, I would like start with a mongo document like this:

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

最终得到这样的 mongo 文档:

and end up with mongo documents like these:

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

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

Ideally this would use the aggregation framework, which I am already using to get my documents to this stage.

推荐答案

从 MongoDB 3.4 开始,我们可以使用 $zip 操作符来压缩我们的数组.

Starting from MongoDB 3.4, we can use the $zip operator to zip our arrays.

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

That being said, we can't get your expected output unless you know length of your array.

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

产生:

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

<小时>

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


If we happen to know the number of elements in each sub-array, we can use the $map variable operator which return an array of sub-document.

$map 表达式中,我们需要使用$arrayElemAt 运算符用于设置我们的字段 A、B 和 C 的值.

In the $map expression, we need to use the $arrayElemAt operator to set the value of our field A, B, and 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 压缩数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆