Mongodb聚合匹配查询,具有完全匹配优先级

时间:2018-08-07 19:17:58

标签: mongodb mongodb-query

我正在尝试对字段进行mongodb正则表达式查询。如果查询找到一个完整匹配,然后再进行部分匹配,我希望查询优先排序。

例如,如果我有一个充满以下条目的数据库。

{
   "username": "patrick"
},
{
   "username": "robert"
},
{
   "username": "patrice"
},
{
   "username": "pat"
},
{
   "username": "patter"
},
{
   "username": "john_patrick"
}

然后我查询用户名“ pat”,我想先返回直接匹配的结果,然后是partials。因此,结果将是有序的['pat','patrick','patrice','patter','john_patrick']。

是否可以仅使用mongo查询来执行此操作?如果是这样,有人可以将我指向详细说明如何实现的资源吗?

这是我尝试用来执行此操作的查询。

db.accounts.aggregate({ $match : 
{ 
    $or : [ 
        { "usernameLowercase" : "pat" },
        { "usernameLowercase" : { $regex : "pat" } }
    ] 
} })

1 个答案:

答案 0 :(得分:1)

给出准确的示例,可以通过以下方式完成-如果您的现实情况稍微复杂一点,则可能会遇到问题,

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

另一种方法是使用$facet,它可以通过启用更复杂的场景而变得更强大,但速度更慢(不过,对于此提议,这里有些人会讨厌我):

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