50

I need to retrieve all the documents that are in my collection in MongoDB, but I cannot figure out how. I have declared my 'collection' like this-

private static IMongoCollection<Project> SpeCollection = db.GetCollection<Project>("collection_Project");

And I followed what is explained in this MongoDB tutorial. I adjusted it for my needs, like-

 var documents = await SpeCollection.Find(new Project()).ToListAsync();

However, I keep having the following error-

MongoDB.Driver.IMongoCollection does not have a definition for 'Find' and the best override of the extension method [superlong stuff]. Find contains non valid arguments.

3 Answers 3

117

Using the current version of the driver (v2.0) you can do that by passing a filter that matches everything:

var documents = await SpeCollection.Find(_ => true).ToListAsync();

They have also added an empty filter (FilterDefinition.Empty) which will arrive in the next version of the driver (v2.1):

var documents = await SpeCollection.Find(Builders<Project>.Filter.Empty).ToListAsync();
1
  • This is not a bad example and it works, however it's very memory intensive for large collections and can lead to Out Of Memory issues. The better option is the solution provided by Minhas Kamal, as you're able to get all results in an enumerable list pulling from the remote collection rather than a localized copy of the collection.
    – Stephan
    Sep 14, 2023 at 16:22
20

Simplest Way

Retrieve all the documents-

var documents = SpeCollection.AsQueryable();

Also convert to JSON object-

var json = Json(documents, JsonRequestBehavior.AllowGet);
1
8

If you want all documents, why not use Find all?

var documents = await SpeCollection.Find(new BsonDocument()).ToListAsync();
1
  • 3
    If you prefer to use lambdas: await SpeCollection.Find(f=>true).ToListAsync();
    – D.Rosado
    May 26, 2015 at 11:28

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.