Strange Behavior with C# Driver, FilterDefintion<T> and LINQ

TLDR: It seems like the c# driver is converting LINQ statements to “true/false” type statements which then causes the mongoDB c# driver to think I have a duplicate filter.

I am building some expressions in the format of Expression<Func<T, bool>> in order to control access to data within MongoDB using the C# driver, latest version as of this post.

Depending on various decisions within the application I end up with a List<Expression<Func<T, bool>>> of different filters I want to use.


x => user.HasDoStuff.Contains(thingImTryingToDo)
x => thingImTryingToTouch.IsLocked


My code builds each of these based on various functions and checks for security. If I combine each individual Expression<Func<T, bool>> object with filter.And(newExpression) it works perfectly. No issues.

However, if I turn them into a FilterDefinition and use “currentFilter &= newFilter”, I ultimately end up with something like

{ \"IsLocked\" : { \"$ne\" : true }, 
\"$or\" : [
	{ \"_id\" : { \"$type\" : -1 } }, 
	{ \"$and\" : [
		{ \"_id\" : ObjectId(\"62d705692f27e4d2887c9760\") }, 
		{ \"_id\" : { \"$type\" : -1 } }] }

Ignoring the specific details of my situation, the key piece here is that I end up with 2 sections of { “_id” : { “$type” : -1 } }, which the mongo driver then complains about, exception to upsert/get/whatever. That part makes sense, it doesn’t like the exact duplicate query.

Soooooo…my core question is:

Why do two false statements such as x => user.Contains(allowedRole) and x => user.CompanyID == “XXXX” both end up as { “_id” : { “$type” : -1 } }?

I can reproduce this with a ~=20 line unit test independent of any specific application code or logic.

Side question: any update on if LINQ support for .Intersect() will be supported for Expression<Func<T, bool>>?
Yes I know I can use FilterDefinition AnyIn, but it would be nice if intersect could convert that statement