mongodb 使用异步的查询投影中的不同行为

Different behavior in mongodb query projection using async

我正在用 C# 实现搜索方法。问题是分数元数据未包含在结果中,导致它在最后一行出现异常。这就像查找是在没有项目子句的情况下完成的。我使用的是 2.2.4.26 版的 c# 驱动程序。

    [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
}

您需要将 query.Project(metaDoc) 的结果分配回查询。就像 LINQ 一样,IFindFluent 接口是不可变的。

query = query.Project(metaDoc);