MetaTextScore 如何 "Injected" 变成 MongoDb Linq 查询

How can MetaTextScore be "Injected" into a MongoDb Linq Query

要进行全文搜索 IMongoQueryable<T> 我们可以使用以下扩展方法。

public static IMongoQueryable<T> WhereText<T>(this IMongoQueryable<T> query, string search) where T: IScored
{
   var filter = Builders<T>.Filter.Text(search);
   return query.Where(_ => filter.Inject())
}

同理,全文搜索怎么打分,一般是按排序排序的:

private static readonly ProjectionDefinition<ProductTypeSearchResult> TextMatchScoreProjection =
   Builders<ProductTypeSearchResult>.Projection.MetaTextScore("Score");
private static readonly SortDefinition<ProductTypeSearchResult> Sort =
   Builders<ProductTypeSearchResult>.Sort.MetaTextScore("score");

collection.Find(...).Project(TextMatchScoreProjection).Sort(Sort);

使用IMongoQueryable<T>

实现

文档中的示例是空白的 https://mongodb.github.io/mongo-csharp-driver/2.8/reference/driver/expressions/#text

给定 class 成员:

private readonly IMongoCollection<SomeType> _someTypes;

注入查询分数的代码如下所示:

private IAggregateFluent<SomeType> CreateSearchQuery(string query, int skipCount, int limitCount)
{
    var filter = Builders<SomeType>.Filter.Text(query);
    return _someTypes
        .Aggregate()
        // Sadly, we must create the query every time because we don't have a way to pass in
        // a filter to an already created query, or change the properties of the filter.
        .Match(filter)
        // Currently the null coalescing operator (??) is not supported in match expressions
        // see https://jira.mongodb.org/browse/CSHARP-2708
        // Currently there is no way to "inject" the text search score
        // see https://jira.mongodb.org/browse/CSHARP-2707
        .AppendStage<SomeType>("{$addFields: {score: {$meta:'textScore'}}}")
        .Sort(_sort)
        .Skip(skipCount)
        .Limit(limitCount);
}