Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB C# Driver - Ignore fields on binding

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?

like image 438
LiamB Avatar asked May 03 '14 19:05

LiamB


People also ask

What is MongoDB C driver?

The MongoDB C Driver, also known as “libmongoc”, is a library for using MongoDB from C applications, and for writing MongoDB drivers in higher-level languages. It depends on libbson to generate and parse BSON documents, the native data format of MongoDB.

Is MongoDB a C++?

Welcome to the documentation site for the official MongoDB C++ driver. You can add the driver to your application to work with MongoDB using the C++11 or later standard.

Is MongoDB free to use?

MongoDB Community is the source available and free to use edition of MongoDB. MongoDB Enterprise is available as part of the MongoDB Enterprise Advanced subscription and includes comprehensive support for your MongoDB deployment.


2 Answers

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.

like image 110
i3arnon Avatar answered Sep 18 '22 10:09

i3arnon


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); 
like image 37
Vetras Avatar answered Sep 17 '22 10:09

Vetras