5

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];
        }
    }

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

But what about returning all of the books from the collection? Doesn't this method work only if there are some conditions? can I just return coll variable after getting it's value?
Sure, you can, with ToArray() or ToList() extension. E.g. database.GetCollection<Book>("Book").ToArray();

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.