MongoDB C# Driver - Ignore fields on binding

C#.NetMongodbMongodb QueryMongodb .Net-Driver

C# Problem Overview


When using a FindOne() using MongoDB and C#, is there a way to ignore fields not found in the object?

EG, example model.

public class UserModel
{
    public ObjectId id { get; set; }
    public string Email { get; set; }
}

Now we also store a password in the MongoDB collection, but do not want to bind it to out object above. When we do a Get like so,

  var query = Query<UserModel>.EQ(e => e.Email, model.Email);
  var entity = usersCollection.FindOne(query);

We get the following error

Element 'Password' does not match any field or property of class 

Is there anyway to tell Mongo to ignore fields it cant match with the models?

C# Solutions


Solution 1 - C#

Yes. Just decorate your UserModel class with the BsonIgnoreExtraElements attribute:

[BsonIgnoreExtraElements]
public class UserModel
{
    public ObjectId id { get; set; }
    public string Email { get; set; }
}

As the name suggests, the driver would ignore any extra fields instead of throwing an exception. More information here - Ignoring Extra Elements.

Solution 2 - C#

Yet Another possible solution, is to register a convention for this.

This way, we do not have to annotate all classes with [BsonIgnoreExtraElements].

Somewhere when creating the mongo client, setup the following:

        var pack = new ConventionPack();
        pack.Add(new IgnoreExtraElementsConvention(true));
        ConventionRegistry.Register("My Solution Conventions", pack, t => true);

Solution 3 - C#

Yes. Another way (instead of editing you model class) is to use RegisterClassMap with SetIgnoreExtraElements.

In your case just add this code when you initialize your driver:

BsonClassMap.RegisterClassMap<UserModel>(cm =>
{
     cm.AutoMap();
     cm.SetIgnoreExtraElements(true);
});

You can read more about ignoring extra elements using class mapping here - Ignoring Extra Elements.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLiamBView Question on Stackoverflow
Solution 1 - C#i3arnonView Answer on Stackoverflow
Solution 2 - C#VetrasView Answer on Stackoverflow
Solution 3 - C#Aviram FirebergerView Answer on Stackoverflow