Kelb56
Kelb56

Reputation: 657

Converting MongoDB documents into c# list of objects

I am trying to write a method which would return all the Book documents from the MongoDB to my mvc application. First, I connect to database, retrieve collection and convert that collection into Json file. Next I create a list which has couple fields specified (name, author, etc.) using serializer i try to deserialize it into list and using a for loop return the list of books. Sadly I get error in the return line (convertion error). Any suggests are welcomed!

public List<Book> getAllBooks() 
    {
        var mongoClient = new MongoClient("mongodb://localhost");
        var database = mongoClient.GetDatabase("SearchForKnowledge");
        var coll = database.GetCollection<BsonDocument>("Book");
        coll.ToJson();

        List<Book> collection = new List<Book>();

        JavaScriptSerializer js = new JavaScriptSerializer();
        collection = (List<Book>)Newtonsoft.Json.JsonConvert.DeserializeObject(coll.ToString());

        for (int i = 0; i < collection.Count(); i++) 
        {
            return collection[i];
        }
    }

Upvotes: 5

Views: 11826

Answers (1)

Eckd
Eckd

Reputation: 358

well, you should try simpler way:

 // add this using first
 using MongoDB.Driver.Linq;

 var coll = database.GetCollection<Book>("Book").AsQueryable<Book>();

And than you can do anything, e.g:

var someBooks = coll.Where(b => b.Year == 2014).Skip(0).Take(10).ToArray();

PS: You need to check out this tutorial: https://mongodb-documentation.readthedocs.org/en/latest/ecosystem/tutorial/use-linq-queries-with-csharp-driver.html

Upvotes: 7

Related Questions