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

后端 未结 5 1094
难免孤独
难免孤独 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:22

    There is also an overload that lets you provide a default value:

    BsonDocument document;
    var firstName = (string) document["FirstName", null];
    // or
    var firstName = (string) document["FirstName", "N/A"];
    

    which is slightly more convenient that using Contains when all you want to do is replace a missing value with a default value.

    Edit: since the 2.0.1 version, it has been deprecated in favor of GetValue:

    var firstName = document.GetValue("FirstName", new BsonString(string.Empty)).AsString;
    

提交回复
热议问题