我在c#中实现了一个搜索方法。问题是结果元数据未包含在结果中,导致它在最后一行上出现异常。就像在没有项目条款的情况下完成查找一样。我使用的是c#驱动程序的2.2.4.26版本。
[HttpPost] public async Task<JsonResult> SearchPost(string str)
{
_client = new MongoClient("mongodb://localhost:27017");
_database = _client.GetDatabase("test");
IMongoCollection<BsonDocument> collection = _database.GetCollection<BsonDocument>("test");
MongoDB.Bson.BsonDocument searchDoc
= MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(
"{$text:{$search:'" + str + "'}}");
MongoDB.Bson.BsonDocument metaDoc
= MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(
"{score: {$meta: 'textScore'}}");
IFindFluent<BsonDocument, BsonDocument> query = collection.Find(searchDoc);
query.Project(metaDoc);
List<BsonDocument> col = await query.ToListAsync();
foreach (BsonDocument doc in col)
{
jsonResult = doc.ToJson();
double score = doc.FirstOrDefault(x => x.Name == "score").Value.AsDouble;
如果我以这种方式设置查询,这在我看来在语法上是等价的,我会得到分数结果:
List<BsonDocument> col = await collection.Find(searchDoc).Project(metaDoc).ToListAsync();
正确的结果如下所示:
{
"_id" : "41608a74-8434-45e4-8404-99922f761dae",
"Path" : "C:\\src\\ba\\mongo\\samples\\xml\\item_20081_v11",
"Files" : [
"content_en-us.xml",
"content_es-mx.xml",
"metadata.xml",
"rubric.xml",
"template.xml",
"translation_en-us.xml",
"translation_es-mx.xml"
],
"ItemXml" : "....be used as a Paramecium cell membrane ...",
"score" : 1.58333333333333
}
答案 0 :(得分:1)
您需要将query.Project(metaDoc)的结果分配回查询。就像LINQ一样,IFindFluent接口是不可变的。
query = query.Project(metaDoc);