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

杀马特。学长 韩版系。学妹 提交于 2019-12-04 22:59:52

问题


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?


回答1:


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;



回答2:


Try the Contains method:

var b = new BsonDocument();
var exists = b.Contains("asdfasdf");



回答3:


An update to Robert's answer, the correct syntax using the C# 2.0 driver is:

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



回答4:


You can use:

var GoodItems = Query.Exists("FirstName");

and than query

People.Find(GoodItems);

That way you'll get only the items that has "FirstName" defined.




回答5:


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<BsonDocument, string>)(d => { var v = d.GetValue("FirstName", null); return v.IsBsonNull ? null : v.AsString; }))(document);


来源:https://stackoverflow.com/questions/6628794/mongodb-c-sharp-getting-bsondocument-for-an-element-that-doesnt-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!