Retrieve Relevance Ordered Result from Text Query on MongoDB Collection using the C# Driver

天涯浪子 提交于 2019-12-07 15:29:25

I was able to get this working through trial and error. The trick is that your data object needs to have a field on it already that will hold the MetaTextScore value. So given the interface:

interface ITextSearchSortable {
    double? TextMatchScore { get; set; }
}

the final function looks like this:

public IEnumerable<T> TextSearch<T>(MongoCollection<T> coll, string text) where T:ITextSearchSortable {
    var cursor = coll.Find(Query.Text(text))
        .SetFields(Fields<T>.MetaTextScore(t => t.TextMatchScore))
        .SetSortOrder(SortBy<T>MetaTextScore(t => t.TextMatchScore));
    foreach(var t in cursor) {
        // prevent saving the value back into the database
        t.TextMatchScore = null;
        yield return t;
    }
}

It's worth noting that TextMatchScore can't have a [BsonIgnore] decoration, or there will be an exception. However, it can have a [BsonIgnoreIfNull] decoration. So by scrubbing the value off the data object before yielding it, the data object can be saved back into the collection without putting in a garbage value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!