Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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't exist of course), instead of returning null, it errors out the app. What's the correct way to check? Do I really have to do a try/catch?

like image 332
googlesearchsentmehere Avatar asked Jul 08 '11 18:07

googlesearchsentmehere


People also ask

What is MongoDB C driver?

The MongoDB C Driver, also known as “libmongoc”, is a library for using MongoDB from C applications, and for writing MongoDB drivers in higher-level languages. It depends on libbson to generate and parse BSON documents, the native data format of MongoDB.

Where is Libmongoc installed?

Now that libbson is compiled, let's install it using msbuild. It will be installed to the path specified by CMAKE_INSTALL_PREFIX . Now let's do the same for the MongoDB C driver. All of the MongoDB C Driver's components will now be found in C:\mongo-c-driver .

Is MongoDB paid?

MongoDB is a NoSQL database that is open source. MongoDB is available in two editions. One is MongoDB Open Source, which is free as part of the Open-Source Community, but for the other editions, you must pay a License fee. When compared to the free edition, this edition has some advanced features.


1 Answers

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;
like image 160
Robert Stam Avatar answered Oct 06 '22 01:10

Robert Stam