c# - Mapping BsonDocument to class but getting error -


this bsondocument extract mongodb collection. deserialize (or map) object/class made in c#.

{   "_id" : objectid("5699715218a323101c663b9a"),   "type": null,   "text": "hello text",   "user":      {       "hair": "brown",       "age": 64     }      } 

this class map/deserialize bsondocument to. fields inside class ones retrieve.

    public class mytype     {         public bsonobjectid _id { get; set; }         public bsonstring text { get; set; }     } 

currently how trying getting error "element 'type' not match field or property of class mytype". not want include "type" field in mytype class.

 var collection = db.getcollection<bsondocument>("data_of_interest");  var filter = new bsondocument();  var mydata = collection.find(filter).firstordefault();  mytype myobject = bsonserializer.deserialize<mytype>(mydata); 

i'm getting error on last line. in example trying 1 document 1 instance of mytype object. interested in how deserialize whole collection list of mytype object or similar isn't 1 bsondocument of documents in collection.

thanks time.

bsonignoreextraelements

flag class [bsonignoreextraelements] attribute. tell c# driver not freak out if there isn't 1:1 match between class properties , mongo record.

[bsonignoreextraelements] public class mytype {     public bsonobjectid _id { get; set; }     public bsonstring text { get; set; } } 

with approach, type , user properties going ignored.

add "catch all" property elements

if you'd rather not ignore elements, add catch property house "undeclared" properties in bson document.

public class mytype {     public bsonobjectid _id { get; set; }     public bsonstring text { get; set; }     [bsonextraelements]     public bsondocument catchall { get; set; } } 

with approach, type , user exist properties of .catchall property.

what's advantage?

one big advantage can "findandreplace" latter without losing data fields aren't mapping.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -