How to create Bson Document with Null value using C# official driver?

早过忘川 提交于 2019-12-01 16:29:40

Depends on the data type of your city variable. If the city variable is of type BsonValue you can use the ?? operator directly:

BsonValue city = null;
var query = Query.EQ("city", city ?? BsonNull.Value);
Console.WriteLine(query.ToJson());

If your city variable is of type string you need an extra conversion cast to make the compiler happy:

string city = null;
var query = Query.EQ("city", (BsonValue)city ?? BsonNull.Value);
Console.WriteLine(query.ToJson());

I assume you are working with BsonDocuments and not C# classs. Because of that, for null values, you need to use BsonNull.Value to represent null values in the database and in queries.

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