0

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

{ 
 "_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
4

1 回答 1

1

用于Contains(string)查看密钥是否存在。

bool assignedToExists = convObject.Contains("assigned_to")

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

TryGetValue(string, out BsonValue)返回一个布尔值,指示检索是否成功(IE:密钥存在)并将该值分配给out变量

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

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

if (assignedToExists)
{
    Console.WriteLine("Assigned to exists, value is {0}", assignedToValue);
}
于 2020-01-16T12:40:48.483 回答