I'm trying to persist an object into a MongoDB, using the following bit of code:

public class myClass
{
    public string Heading { get; set; }
    public string Body { get; set; } 
}

static void Main(string[] args)
{
    var mongo = MongoServer.Create();
    var db = mongo.GetDatabase("myDb");
    var col = db.GetCollection<BsonDocument>("myCollection");
    var myinstance = new myClass();
    col.Insert(myinstance);

    var query = Query.And(Query.EQ("_id", new ObjectId("4df06c23f0e7e51f087611f7)));
    var res = col.Find(query);
    foreach (var doc in res)
    {
        var obj = BsonSerializer.Deserialize<myClass>(doc);
    }
}

However I get the following exception 'Unexpected element: _id' when trying to Deserialize the document.

So do I need to Deserialize in another way?? What is the preferred way of doing this?

TIA

Søren

link|flag

1 Answer

This is becuase when you store your class in mongodb driver automatically generate _id and during deserialization driver finds _id in mongodb, but can't find in your class and throw exception but default.

If you no need to know id from your class you can add BsonIgnoreExtraElements attribute to your class(and everything will work):

  [BsonIgnoreExtraElements]
  public class myClass

Or you can add id to your class and mark it as BsonId:

public class myClass
{
    [BsonId]
    public ObjectId Id {get;set;}
    public string Heading { get; set; }
    public string Body { get; set; } 
}

Also you can use following code and driver automatically deserialize class for you:

var res = col.FindAs<myClass>(query);
link|flag

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.