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

MongoDB:Agregación usando $cond con $regex

ACTUALIZACIÓN: Comenzando con MongoDB v4.1.11, finalmente parece haber una buena solución para su problema que está documentado aquí .

Respuesta original:

Como escribí en los comentarios anteriores, $regex no funciona dentro de $cond a partir de ahora. Hay un ticket de JIRA abierto para eso pero es, err, bueno, abierto...

En su caso específico, tendería a sugerirle que resuelva ese tema en el lado del cliente a menos que esté tratando con cantidades locas de datos de entrada de los cuales siempre solo devolverá pequeños subconjuntos. A juzgar por su consulta, parecería que siempre va a recuperar todos los documentos agrupados en dos grupos de resultados ("Sí" y "No").

Si no quiere o no puede resolver ese tema en el lado del cliente, aquí hay algo que usa $faceta (Se requiere MongoDB>=v3.4):no es particularmente rápido ni demasiado bonito, pero podría ayudarlo a comenzar.

db.captions.aggregate([{
    $facet: { // create two stages that will be processed using the full input data set from the "captions" collection
        "CallToActionYes": [{ // the first stage will...
            $match: { // only contain documents...
                "plainText": /leave\sa\scomment/i // that are allowed by the $regex filter (which could be extended with multiple $or expressions or changed to $in/$nin which accept regular expressions, too)
            }
        }, {
            $addFields: { // for all matching documents...
                "CallToAction": "Yes" // we create a new field called "CallsToAction" which will be set to "Yes"
            }
        }],
        "CallToActionNo": [{ // similar as above except we're doing the inverse filter using $not
            $match: {
                "plainText": { $not: /leave\sa\scomment/i }
            }
        }, {
            $addFields: {
                "CallToAction": "No" // and, of course, we set the field to "No"
            }
        }]
    }
}, {
    $project: { // we got two arrays of result documents out of the previous stage
        "allDocuments" : { $setUnion: [ "$CallToActionYes", "$CallToActionNo" ] } // so let's merge them into a single one called "allDocuments"
    }
}, {
    $unwind: "$allDocuments" // flatten the "allDocuments" result array
}, {
    $replaceRoot: { // restore the original document structure by moving everything inside "allDocuments" up to the top
        newRoot: "$allDocuments"
    }
}, {
    $project: { // include only the two relevant fields in the output (and the _id)
        "videoId": 1,
        "CallToAction": 1
    }
}])

Como siempre con el marco de agregación, puede ser útil eliminar etapas individuales del final de la canalización y ejecutar la consulta parcial para comprender lo que hace cada etapa individual.