MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Proiezione in un altro tipo usando C# SDK

Ho trovato il modo per eseguire la mappatura che desideri:

collection
    .Find(Builders<MyType>.Filter.AnyIn(x => x.Documents, new[] { "c" }))
    .Project(Builders<MyType>.Projection.Exclude(c => c.Documents))
    .As<MySubType>()
    .ToList();

Ma prima dovresti registrare la mappatura per il tuo sottotipo ignorando l'elemento aggiuntivo. Non lo capisco al 100%, sembra essere un bug del driver, non riceve Documents da mongo, ma sa, quel MyType ha tale proprietà. Nota, dovresti registrare la mappatura della tua classe, prima per prima cosa crei una raccolta di questo tipo.

if (!BsonClassMap.IsClassMapRegistered(typeof(MySubType)))
{
    BsonClassMap.RegisterClassMap<MySubType>(cm =>
    {
        cm.AutoMap();
        cm.SetIgnoreExtraElements(true);
    });
}

L'ho fatto con dati di esempio :

var toInsert = new List<MyType>
{
    new MyType {Id = 1, Name = "bla", Documents =new List<string> {"a", "b", "v"}},
    new MyType {Id = 2, Name = "ada", Documents =new List<string> {"c", "d", "r"}},
};

E potrebbe ottenere l'output previsto:

collection
    .Find(Builders<MyType>.Filter.AnyIn(x => x.Documents, new[] { "c" }))
    .Project(Builders<MyType>.Projection.Exclude(c => c.Documents))
    .As<MySubType>()
    .ToList()
    .Dump();