10

I have objects with 3 string fields Country, Province, City. They can contain null or some string name.

I wanna query all data with the exact same values.

For Example i need all data where

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

I created BsonDocument:

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

But null field was thrown away and document looks like:

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

If i'm triing to use

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

I have exception saying that parametr cant be null.

As i see in documentation there is no problem in building query cheking if value equals null. So that is a problem with C# driver. Any ideas how to solve this problem?

2 Answers 2

18

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());
Sign up to request clarification or add additional context in comments.

Comments

3

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.

3 Comments

Have no idea how to use it in this case. Cant write something like userLocation.City??BsonNull.Value there are not of the same type. There should be very simple way that i just dont see.
try this: Query.EQ("GeoPosition.City", BsonValue.Create(userLocation.City))
Craig, that throws an error if userLocation.City is null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.