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

后端 未结 2 1461
失恋的感觉
失恋的感觉 2021-01-17 18:18

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.

Fo

相关标签:
2条回答
  • 2021-01-17 18:45

    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.

    0 讨论(0)
  • 2021-01-17 18:49

    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());
    
    0 讨论(0)
提交回复
热议问题