Get All 'documents' from MongoDB 'collection'

ε祈祈猫儿з 提交于 2019-12-03 10:47:37

问题


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.


回答1:


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



回答2:


Simplest Way

Retrieve all the documents-

var documents = SpeCollection.AsQueryable();

Also convert to JSON object-

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



回答3:


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

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


来源:https://stackoverflow.com/questions/30453780/get-all-documents-from-mongodb-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!