Bla*_*ell 2 c# mongodb mongodb-query mongodb-.net-driver
我正在尝试对集合进行文本查询并按文本匹配顺序检索结果。文档很好地解释了如何在 shell 中执行此操作:
db.articles.find(
{ status: "A", $text: { $search: "coffee cake" } },
{ score: { $meta: "textScore" } }
).sort( { date: 1, score: { $meta: "textScore" } } )
Run Code Online (Sandbox Code Playgroud)
但它需要将附加score字段从 find投影到排序中。
在 C# 中,我有一个如下所示的函数:
public IEnumerable<T> TextSearch<T>(MongoCollection<T> coll, string text) {
var cursor = coll.Find(Query.Text(text))
.SetSortOrder(SortBy<T>.MetaTextScore(???));
foreach(var t in cursor) {
// strip projected score from value
yield return t;
}
}
Run Code Online (Sandbox Code Playgroud)
但我缺少如何将“textScore”值投影到我的结果中,以便我可以将列指定为MetaTextScorein SetSortOrder。
我能够通过反复试验来解决这个问题。诀窍是你的数据对象需要已经有一个字段来保存MetaTextScore值。所以给出了界面:
interface ITextSearchSortable {
double? TextMatchScore { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
最终函数如下所示:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
值得注意的是TextMatchScore 不能有[BsonIgnore]装饰品,否则会有例外。但是,它可以有[BsonIgnoreIfNull]装饰。因此,通过在产生数据对象之前清除数据对象的值,可以将数据对象保存回集合中,而无需放入垃圾值。