Zip arrays with MongoDB

前端 未结 1 1700
生来不讨喜
生来不讨喜 2021-01-14 18:07

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 m

相关标签:
1条回答
  • 2021-01-14 18:53

    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
            }
        ]
    }
    
    0 讨论(0)
提交回复
热议问题