如何使用 Mongodb C# 驱动程序检查 BsonDocument 中是否存在密钥?

How to check if key exists in BsonDocument or not using Mongodb C# driver?

我正在使用这样的 C# 驱动程序从 mongodb 接收数据 (BsonDocument)

{ 
 "_id":ObjectId("5c8730688a247070ca5e4a15"),
 "visitorEmail":"UnRegistered",
 "visitorName":"Guest040704",
 "agentEmail":"salman@blauda.com",
 "sessionid":"5c86e0f88a247070ca5e48e6",
 "createdOn":"2019-03-12T04:07:04.455Z",
 "state":3,
 "messages":[ 

  ],
"messageReadCount":0,
"lastMessage":{ 
   "_id":ObjectId("5c8730688a247070ca5e4a16"),
    "from":"MEHAK",
    "to":"Guest040704",
    "body":"Hello.. How may i Help You ?",
    "cid":ObjectId("5c8730688a247070ca5e4a15"),
    "date":"2019-03-12T04:07:04.455Z",
    "type":"Agents",
     "attachment":false,
     "filename":null
   },
 "entertained":true,
 "endingDate":"2020-01-15T05:47:37.170Z"
}

现在我想检查此文档中是否存在关键字 "assigned_to"。所以我尝试了这个:

convObject.TryGetValue("assigned_to", out isAssignedToExist);
Console.WriteLine("is assigned to ---- : "+isAssignedToExist);

无论密钥是否存在,我都会收到这样的错误,而不是结果:

ErorrSystem.Collections.Generic.KeyNotFoundException: Element 'assigned_to' not found.at 
MongoDB.Bson.RawBsonDocument.GetValue(String name) at 
sqs_processor.QueueService.ExecuteAsync(CancellationToken stoppingToken) in 
D:\OfficeProjects\beelinksanalytics\Services\queueService.cs:line 100

使用Contains(string)查看键值是否存在。

bool assignedToExists = convObject.Contains("assigned_to")

您的堆栈跟踪还表明您使用了 GetValue,而不是您的问题所暗示的 TryGetValue

TryGetValue(string, out BsonValue) returns 一个布尔值,指示检索是否成功(即:键存在)并将该值分配给 out 变量

这当然可以简化,我已经扩展了冗长的代码。

bool assignedToExists = convObject.TryGetValue("assigned_to", out BsonValue assignedtoValue);

if (assignedToExists)
{
    Console.WriteLine("Assigned to exists, value is {0}", assignedToValue);
}