Search code examples
c#mongodb.net-corebsondocument

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

Solution

  • 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 (I.E: 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);
    }