[CSHARP-2902] Wrong conversion of Expression x => !x.value into filter if value is boolean Created: 16/Jan/20  Updated: 27/Oct/23  Resolved: 04/Feb/20

Status: Closed
Project: C# Driver
Component/s: API
Affects Version/s: 2.9.3
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Victor Trusov Assignee: Dmitry Lukyanov (Inactive)
Resolution: Works as Designed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Model

public class MyClass
{   
   public ObjectId Id { get; set; }
 
   public bool MyBoolean { get; set; }
   public string Name { get; set; }
}

Filter with expression

var filter = Collection.Find(x => !x.MyBoolean)
// filter.ToString()

converts into

{ 
   "MyBoolean": { $ne: true}
}

but should converts into

{ "MyBoolean": false }

cause its boolean and it is not ignored (can't be `BsonNull`).

It's important in cases where you want to use sort by index and had compound index with "MyBoolean" in it.
So now if you had index like {MyBoolean: 1, Name: 1} this query can't use it:

Collection.Find(x => !x.MyBoolean).SortBy(x => x.Name)

because of filter {"MyBoolean":{$ne:true}} and you have to write it like this:

Collection.Find(x => x.MyBoolean == false).SortBy(x => x.Name)

to get filter

{ "MyBoolean": false }

and achieve sorting by index.



 Comments   
Comment by Dmitry Lukyanov (Inactive) [ 30/Jan/20 ]

Hello mercurochromo@gmail.com,

The c# driver considers the queries !x.MyBoolean and x.MyBoolean == false as not fully equivalents. Based on this the generated mongo queries are different a bit.
So, for your goal you need to use: x => x.MyBoolean == false

Comment by Victor Trusov [ 17/Jan/20 ]

https://stackoverflow.com/questions/59778226/filter-by-boolean-false-in-mongodb-driver

Generated at Wed Feb 07 21:43:50 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.