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

En MongoDB, cómo realizar una consulta en función de si un campo de cadena contiene otro

Puedes hacer esto con $where creando un RegExp para string1 y luego probarlo contra string2 :

db.test.find({$where: 'RegExp(this.string1).test(this.string2)'})

Sin embargo, si usa MongoDB 3.4+, puede hacerlo de manera más eficiente usando $indexOfCP operador de agregación:

db.test.aggregate([
    // Project  the index of where string1 appears in string2, along with the original doc.
    {$project: {foundIndex: {$indexOfCP: ['$string2', '$string1']}, doc: '$$ROOT'}},
    // Filter out the docs where the string wasn't found
    {$match: {foundIndex: {$ne: -1}}},
    // Promote the original doc back to the root
    {$replaceRoot: {newRoot: '$doc'}}
])

O más directamente usando también $redact :

db.test.aggregate([
    {$redact: {
        $cond: {
            if: { $eq: [{$indexOfCP: ['$string2', '$string1']}, -1]},
            then: '$$PRUNE',
            else: '$$KEEP'
        }
    }}
])