Retrieve data from mongodb using C# driver

孤街醉人 提交于 2019-12-04 02:36:30

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();

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

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.

Yossi Lev

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!