MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Mongodb aggregierte Übereinstimmungsabfrage mit Priorität auf vollständige Übereinstimmung

In Anbetracht Ihres genauen Beispiels könnte dies auf folgende Weise erreicht werden - wenn Ihr reales Szenario etwas komplexer ist, können Sie jedoch auf Probleme stoßen:

db.accounts.aggregate([{
    $match: {
        "username": /pat/i // find all documents that somehow match "pat" in a case-insensitive fashion
    }
}, {
    $addFields: {
        "exact": { 
            $eq: [ "$username", "pat" ] // add a field that indicates if a document matches exactly
        },
        "startswith": { 
            $eq: [ { $substr: [ "$username", 0, 3 ] }, "pat" ] // add a field that indicates if a document matches at the start
        }

    }
}, {
    $sort: {
        "exact": -1, // sort by our primary temporary field
        "startswith": -1 // sort by our seconday temporary
    }
}, {
    $project: {
        "exact": 0, // get rid of the "exact" field,
        "startswith": 0 // same for "startswith"
    }
}])

Eine andere Möglichkeit wäre die Verwendung von $facet was sich als etwas leistungsfähiger erweisen könnte, indem es komplexere Szenarien ermöglicht, aber langsamer ist (einige Leute hier werden mich jedoch für diesen Vorschlag hassen):

db.accounts.aggregate([{
    $facet: { // run two pipelines against all documents
        "exact": [{ // this one will capture all exact matches
            $match: {
                "username": "pat"
            }
        }],
        "others": [{ // this one will capture all others
            $match: {
                "username": { $ne: "pat", $regex: /pat/i }
            }
        }]
    }
}, {
    $project: {
        "result": { // merge the two arrays
            $concatArrays: [ "$exact", "$others" ]
        }
    }
}, {
    $unwind: "$result" // flatten the resulting array into separate documents
}, {
    $replaceRoot: { // restore the original document structure
        "newRoot": "$result"
    }
}])