Zip arrays with MongoDB

Deadly 提交于 2019-12-19 09:33:50

问题


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.

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

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.


回答1:


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

which produces:

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

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.

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

which produces:

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


来源:https://stackoverflow.com/questions/31164156/zip-arrays-with-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!