In Visual Studio you can write below line of code and try to inspect it by hovering:
var query = await col.Find(f=>f.Str.Length>2)
What happens is that MongoDB will transalte it into regular expression like {find({ "Str" : /^.{3,}$/s })}
and this regex gets executed on the database side. Nothing unexpected. The problem occurs when you change Str
into Id
which gets translated into:
{find({ "_id" : /^.{3,}$/s })}
and you get no result as your field's name is still Id
. The reason why it's happening is described here. So MongoDB driver by convention infers that field named Id
should be translated into _id
. To fix that you can explicitly specify on your data model which field should be considered as _id
using BsonId
attribute:
public class ModelClass
{
[BsonId]
public ObjectId RealId { get; set; }
public string Id { get; set; }
}
EDIT:
To apply type conversion (int -> string) you have to rely on $toString operator introduced in MongoDB. The idea is simple: you add new field using $addFields and then run $strLenCP on it to verify string length. Unfortunately there's no easy way to do it in C# using strongly typed way so you can use BsonDocument
class which lets you use strings as Aggregation Pipeline definition:
var q = Col.Aggregate()
.AppendStage<BsonDocument>(BsonDocument.Parse("{ $addFields: { AuthTypeInt: { $toString: \"$AuthType\" } } }"))
.Match(BsonDocument.Parse("{ $expr: { $gt: [ { \"$strLenCP\": \"$AuthTypeInt\" }, 2 ] } }"));
var data = await q.ToListAsync();
The code looks ugly but it should be a way faster than running plain JavaScript (more here)