Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get All 'documents' from MongoDB 'collection'

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.

like image 240
NicolasR Avatar asked May 26 '15 08:05

NicolasR


People also ask

How fetch all data from collection in MongoDB?

Fetch all data from the collection If we want to fetch all documents from the collection the following mongodb command can be used : >db. userdetails. find(); or >db.

Which query object selects all documents in a MongoDB collection?

A compound query can specify conditions for more than one field in the collection's documents. Implicitly, a logical AND conjunction connects the clauses of a compound query so that the query selects the documents in the collection that match all the conditions.


2 Answers

Simplest Way

Retrieve all the documents-

var documents = SpeCollection.AsQueryable(); 

Also convert to JSON object-

var json = Json(documents, JsonRequestBehavior.AllowGet); 
like image 31
Minhas Kamal Avatar answered Sep 22 '22 18:09

Minhas Kamal


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(); 
like image 148
i3arnon Avatar answered Sep 21 '22 18:09

i3arnon