when I use IsEmpty in Filter it throw Exception below.
System.NotSupportedException: Serializer for System.Collections.Immutable.ImmutableList`1[System.String] does not represent members as fields.
Here is the source code.
BsonSerializer.RegisterGenericSerializerDefinition(typeof(ImmutableList<>), typeof(ImmutableListSerializer<>));
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("tdb");
var collection = database.GetCollection<Test>("tests");
List<Test> data = [
new Test("1", ["a", "b"]),
new Test("2", []),
new Test("3"),
];
var result1 = data.Where(t => t.Names != null && t.Names.IsEmpty);
foreach (var t in result1)
{
Console.WriteLine(t.ToString());
}
try
{
collection.InsertMany(data);
// var filter = Builders<Test>.Filter.Where(t => t.Names != null && t.Names.Count == 0); // works
var filter = Builders<Test>.Filter.Where(t => t.Names != null && t.Names.IsEmpty); // not works
var result2 = collection.Find(filter).ToEnumerable();
foreach (var t in result2)
{
Console.WriteLine(t.ToString());
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
database.DropCollection("tests");
}
public record Test(string Id, ImmutableList<string>? Names = null);
public class ImmutableListSerializer<TValue> : EnumerableInterfaceImplementerSerializerBase<ImmutableList<TValue>, TValue>
{
protected override object CreateAccumulator() => new List<TValue>();
protected override ImmutableList<TValue> FinalizeResult(object accumulator)
=> [.. ((List<TValue>)accumulator)];
}