10

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!

4 Answers 4

11

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();
Sign up to request clarification or add additional context in comments.

2 Comments

hi Andrew Orsich, I've inserted document using BsonDocument and mongodb auto generate ObjectId for document and store it, when i use MongoCollection<Blog> and call FindAllAs<Blog> method, ReadString method throws exception. So i change MongoCollection<Blog> to MongoCollection<BsonDocument> and traversal cursor object in foreach statement to convert each document to blog object. Anyway, ur reply help me resolved my problem, thank u :)
An easier fix would be to change the datatype of your ID to ObjectId and decorate it with [BsonId]. I ran into the same error message, and making that change fixed it for me.
3

Retrieving the data from the MongoDB using C# is pretty simple and there are three different ways the data can be rolled out for frontend

  1. List
  2. Cursor
  3. linq

    using (var cursor = await col.Find(new BsonDocument()).ToCursorAsync())
    {
     while (await cursor.MoveNextAsync())
     {
        foreach (var doc in cursor.Current)
        {
            Console.WriteLine(doc);
        }
      }
    }
    

the above code Shows to retrieve the data using cursors. Referrence

Comments

1

Take a look at my sample project at github. Off late, I've become really interested in MongoDB. This application shows many useful things that might interest you as well; repository pattern with MongoDB.

Comments

0

The type and name of the id member should be different as follows

public ObjectId Id { get; set; }

Where ObjectId is in the namespace MongoDB.Bson

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.