简体   繁体   中英

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.

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

Simplest Way

Retrieve all the documents-

var documents = SpeCollection.AsQueryable();

Also convert to JSON object-

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

如果您想要所有文档,为什么不使用Find all

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM