Skip to content Skip to sidebar Skip to footer

Aggregate Multiple Arrays Into One Huge Array With MongoDB

I got a collection with documents such as those: { '_id': 0, 'pictures': [ { 'path': '/path/to/first/picture.jpg', 'web': 'true' },

Solution 1:

You can use the $filter and the $setUnion/$concatArrays operators to concatenate and filter your documents. Also you need to use the $ifNull operator to replace the missing field with empty array.

db.collection.aggregate([
    { "$project": { 
        "web_images": { 
            "$filter": { 
                "input": { 
                    "$setUnion": [ 
                        { "$ifNull": [ "$pictures", [] ] },
                        { "$ifNull": [ "$logos", [] ] }
                    ]
                }, 
                "as": "p", 
                "cond": { "$eq": [ "$$p.web", "true" ] } 
            } 
        } 
    }},
    { "$match": { "web_images.0": { "$exists": true } } }
])

Post a Comment for "Aggregate Multiple Arrays Into One Huge Array With MongoDB"