简体   繁体   中英

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

I am receiving data (BsonDocument) from mongodb using a C# driver like this:

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

Now I want to check if the key "assigned_to" exists in this document or not. So i tried this:

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

I am getting an error like this instead of the result whether key exists or not:

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

Use Contains(string) to see if a key exists.

bool assignedToExists = convObject.Contains("assigned_to")

Your stack trace also indicates that you have used GetValue , not TryGetValue as your question suggests.

TryGetValue(string, out BsonValue) returns a boolean value which indicates if the retrieval was successful (IE: the key exists) and the value is assigned to the out variable

This of course can be simplified, I've expanded the code for verbosity.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM