How to create a Bson document with a null value using the official C # driver?

I have objects with 3 string fields Country, province, city. They can contain zero or some string name.

I want to query all the data with the same values.

For example, I need all the data where

City = null, Province = "WA", Country = "USA" 

I created a BsonDocument:

 var lookup = new QueryDocument { {"GeoPosition.City", userLocation.City}, {"GeoPosition.Province", userLocation.Province}, {"GeoPosition.Country", userLocation.Country} }; 

But an empty field was thrown away and the document looked like this:

 { "GeoPosition.Province" : "WA", "GeoPosition.Country" : "USA" } 

If I try to use

 Query.EQ("GeoPosition.City", userLocation.City) 

I have an exception saying that the parameter cannot be null.

As I see in the documentation, there is no problem building a cheking request if the value is null. So this is a problem with the C # driver. Any ideas how to solve this problem?

+6
source share
2 answers

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

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

If your city variable has a type string, you need to add an extra conversion code to make the compiler happy:

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

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

0
source

Source: https://habr.com/ru/post/916252/


All Articles