I am implementing a search method in c#. The issue is that the score metadata is not included in the result, causing it to exception on the last line. It's like the find is being done without the project clause. I am using version 2.2.4.26 of the c# driver.
[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;
If I set the query up this way, which seems to me syntactically equivalent, I do get the score result back:
List<BsonDocument> col = await collection.Find(searchDoc).Project(metaDoc).ToListAsync();
The correct result looks like this:
{
"_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
}