Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB C# Driver: Ignore Property on Insert

I am using the Official MongoDB C# Drive v0.9.1.26831, but I was wondering given a POCO class, is there anyway to ignore certain properties from getting inserted.

For example, I have the following class:

public class GroceryList {     public string Name { get; set; }     public FacebookList Owner { get; set; }     public bool IsOwner { get; set; } } 

Is there a way, for the IsOwner to not get inserted when I insert a GroceryList object? Basically, I fetch the object from the database then set the IsOwner property in the app layer and then return it back to the controller, which than maps the object to a view model.

Hope my question makes sense. thanks!

like image 392
Abe Avatar asked Feb 03 '11 23:02

Abe


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

It looks like the [BsonIgnore] attribute did the job.

public class GroceryList : MongoEntity<ObjectId> {     public FacebookList Owner { get; set; }     [BsonIgnore]     public bool IsOwner { get; set; } } 
like image 129
Abe Avatar answered Sep 23 '22 10:09

Abe


Alternatively, if you don't want to use the attribute for some reason (e. g. in case you don't want to bring an extra dependency to MongoDB.Bson to your DTO), you can do the following:

BsonClassMap.RegisterClassMap<GroceryList>(cm => {   cm.AutoMap();   cm.UnmapMember(m => m.IsOwner); }); 
like image 21
iredchuk Avatar answered Sep 21 '22 10:09

iredchuk