MongoDB C# - Getting BsonDocument for an Element that doesn't exist

后端 未结 5 1175
难免孤独
难免孤独 2021-02-09 07:53

So I have a BsonDocument b (let\'s say it has FirstName, LastName, Age), which you could access as b[\"FirstName\"], etc...

If I try to do b[\"asdfasdf\"] (which doesn\'

5条回答
  •  花落未央
    2021-02-09 08:20

    With the C# driver version 2, it might not be enough to check the existence of the field. The line:

    var firstName = report.GetValue("FirstName", null);
    

    will return a BsonNull object if FirstName is actually null in the db, when in fact you'd like to get a string. One way to take this into consideration in a one line code is:

    BsonDocument document;
    string firstName = ((Func)(d => { var v = d.GetValue("FirstName", null); return v.IsBsonNull ? null : v.AsString; }))(document);
    

提交回复
热议问题