c# mongodb or查询_使用C#驱动程序从MongoDB集合上的文本查询检索相关性排序结果...

本文详细介绍了如何在C#中使用MongoDB进行文本查询,并通过元数据`textScore`进行排序。作者分享了解决方案,包括如何在数据对象中预设MetaTextScore字段以实现正确排序。同时,讨论了避免数据污染的方法和注意事项。
摘要由CSDN通过智能技术生成

I am attempting to text query a collection and retrieve the results in the text match order. The docs explain pretty well how to do this in the shell:

db.articles.find(

{ status: "A", $text: { $search: "coffee cake" } },

{ score: { $meta: "textScore" } }

).sort( { date: 1, score: { $meta: "textScore" } } )

but it requires the projection of the additional score field from the find into the sort.

In C#, I have a function that looks like this:

public IEnumerable TextSearch(MongoCollection coll, string text) {

var cursor = coll.Find(Query.Text(text))

.SetSortOrder(SortBy.MetaTextScore(???));

foreach(var t in cursor) {

// strip projected score from value

yield return t;

}

}

but I am missing how to project the "textScore" value into my results, so that I can specify the column to MetaTextScore in SetSortOrder.

解决方案

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 TextSearch(MongoCollection coll, string text) where T:ITextSearchSortable {

var cursor = coll.Find(Query.Text(text))

.SetFields(Fields.MetaTextScore(t => t.TextMatchScore))

.SetSortOrder(SortByMetaTextScore(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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值