sql >> Base de Datos >  >> NoSQL >> MongoDB

Agregue varias matrices en una gran matriz con MongoDB

Puede usar el $filter y el $setUnion /$concatArrays operadores para concatenar y filtrar sus documentos. También debe usar $ifNull operador para reemplazar el campo faltante con una matriz vacía.

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