I have the following simple join query.
var queryable = from claim in AtomDbMapper.UserClaims.AsQueryable() join user in AtomDbMapper.Users.AsQueryable() on claim.UserId equals user.Id into users where claim.ClaimType == "Moderator" select users.First()
Now I want to perform a filter operation on the users that are returned.
If I perform the filter query using the LINQ functions as follows
var whereQuery = queryable.Where(x => x.NormalizedUsername == "PAPLABROS");
The following query is generated by the driver.
{aggregate([{ "$lookup" : { "from" : "Users", "localField" : "UserId", "foreignField" : "_id", "as" : "users" } }, { "$match" : { "ClaimType" : "Moderator" } }, { "$project" : { "__fld0" : { "$arrayElemAt" : ["$users", 0] }, "_id" : 0 } }, { "$match" : { "__fld0.NormalizedUsername" : "PAPLABROS" } }])}
which works perfectly fine.
Now, if I use a FilterDefinition along with the Inject() method as follows.
var filter = Builders<UserEntity>.Filter.Eq(x => x.NormalizedUsername, "PAPLABROS"); var filterQuery = queryable.Where(x => filter.Inject());
The following query is generated by the driver.
{aggregate([{ "$lookup" : { "from" : "Users", "localField" : "UserId", "foreignField" : "_id", "as" : "users" } }, { "$match" : { "ClaimType" : "Moderator" } }, { "$project" : { "__fld0" : { "$arrayElemAt" : ["$users", 0] }, "_id" : 0 } }, { "$match" : { "NormalizedUsername" : "PAPLABROS" } }])}
which when executed doesn't yield any results.
Notice that the difference between those 2 queries is that the second one doesn't specify the __fld0 field at the last match operation. It appears to be an issue when using the Inject() method along with any IMongoQueryable that represents an aggregation query.