Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve data from mongodb using C# driver

I'm using official mongodb driver for c# in my test project and i've already insert document from c# web application to mongodb. In mongo console, db.blog.find() can display entries I've inserted. but when i tried to retrieve them, .net throw a exception

"System.InvalidOperationException: ReadString can only be called when CurrentBsonType is String, not when CurrentBsonType is ObjectId."

my entity class is very simple

namespace MongoDBTest
{
    public class Blog
    {
        public String _id
        {
            get;
            set;
        }

        public String Title
        {
            get;
            set;
        }
    }
}

and this is my retrieve code

public List<Blog> List()
{
    MongoCollection collection = md.GetCollection<Blog>("blog");
    MongoCursor<Blog> cursor = collection.FindAllAs<Blog>();
    cursor.SetLimit(5);
    return cursor.ToList();
}

can anybody help me out? thanks!

like image 301
Ken Qiu Avatar asked Jul 21 '11 06:07

Ken Qiu


1 Answers

I suppose you just need mark your blog Id with BsonId (and insert id yourself) attribute:

public class Blog
{
    [BsonId]
    public String Id {get;set;}

    public String Title{get;set;}
}

And all should be okay. Issue was because you not marked what field will be Mongodb _id and driver generated _id field with type ObjectId. And when driver trying deserialize it back he can't convert ObjectId to String.

Complete example:

MongoCollection collection = md.GetCollection<Blog>("blog");
var blog = new Blog(){Id = ObjectId.GenerateNewId().ToString(), 
                      Title = "First Blog"};
collection .Insert(blog);

MongoCursor<Blog> cursor = collection.FindAllAs<Blog>();
cursor.SetLimit(5);

var list = cursor.ToList();
like image 108
Andrew Orsich Avatar answered Sep 28 '22 07:09

Andrew Orsich