Mongo version: 5.0.5 (Docker image and Atlas cluster show same behaviour)
C# Driver version: 2.14.1
Here is the description of the strange behaviour:
I
n mongosh
(or Compass):
Running test.find()
returns two documents, both with _t: "Unknown"
.
Running test.find({_t: "Unknown"})
returns 0 documents.
Running test.find({_t: "X"})
or test.find({_t: "Y"})
returns 1 document, but the value of _t: "Unknown"
is still shown in the returned document.
How to get into this state:
Have an instance of Mongo running. Create a new .NET 6 console project using the NuGet MongoDB.Driver 2.14.1. Replace everything in Program.cs
with the code below (editing the connection string if necessary). If you don’t understand this code, do not run in locally, that’s dangerous!
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
const string conventionName = "test";
var conventionPack = new ConventionPack
{
new CamelCaseElementNameConvention(),
new EnumRepresentationConvention(BsonType.String)
};
ConventionRegistry.Remove(conventionName);
ConventionRegistry.Register(conventionName, conventionPack, t => true);
BsonClassMap.RegisterClassMap<Document>();
BsonClassMap.RegisterClassMap<XDocument>(x =>
{
x.AutoMap();
x.SetDiscriminator(Type.X.ToString());
});
BsonClassMap.RegisterClassMap<YDocument>(x =>
{
x.AutoMap();
x.SetDiscriminator(Type.Y.ToString());
});
var client = new MongoClient("mongodb://localhost:27017");
var db = client.GetDatabase("test");
var coll = db.GetCollection<Document>("docs");
var x = new XDocument();
var y = new YDocument();
await coll.InsertOneAsync(x);
await coll.InsertOneAsync(y);
public class Document
{
[BsonElement("_t")]
public Type Type { get; set; }
}
public class XDocument : Document
{
public string X { get; set; } = "hello x!";
}
public class YDocument : Document
{
public string Y { get; set; } = "hello y!";
}
public enum Type
{
Unknown = 0,
X,
Y
}