4

I can't figure it out how to make a Read function on mongoDB in asp.net mvc 5. I have this part of code in controller:

 public HomeController() {
           var mongoClient = new MongoClient(Settings.Default.EmployeesConnectionString);
           var database= mongoClient.GetDatabase("football");
           var coll = database.GetCollection<BsonDocument>("Footballers");

As you can see I have database and collection paths saved in a variables so it would be easier to navigate. I also tested it out, I managed to create a new collection in mongodb so I assume that this is correct. My question is what should I write further to get a whole collection returned? Should it be in the List? After that I will try to return it in a webpage, so if you have any remarks on this, please let me know also.

Mafii
  • 7,227
  • 1
  • 35
  • 55
Kelb56
  • 587
  • 3
  • 8
  • 21
  • 1
    This may help https://stackoverflow.com/questions/30453780/get-all-documents-from-mongodb-collection – JanMer Apr 14 '16 at 08:15
  • What does ASP.NET MVC have to do with MongoDB queries? – Panagiotis Kanavos Apr 14 '16 at 08:15
  • 1
    @JanWidmer I saw this before, but it did not help. Im not really familliar with async and await methods so I thought there has to be another way. – Kelb56 Apr 14 '16 at 08:21
  • @Kelb56 async/await has nothing to do with how you retrieve data. It isn't hard to use either - just add the `await` keyword. I suggest you get familiar with using `await` as a lot of classes have *only* asynchronous interfaces, eg HttpClient – Panagiotis Kanavos Apr 14 '16 at 08:30
  • Instead of `ToListAsync` just call `ToList`. The code won't look any different (that's how easy `async/await` is), you'll just have to wait until all data is retrieved – Panagiotis Kanavos Apr 14 '16 at 08:34
  • 1
    I tried this, still no success, seems like i made a stupid mistake :? var documents = coll.Find(new BsonDocument()).ToList(); Console.WriteLine(documents); Console.ReadLine(); – Kelb56 Apr 14 '16 at 08:43
  • 1
    What does "no success" mean? You didn't get any results? You got an exception? A compilation error? – Panagiotis Kanavos Apr 14 '16 at 09:45
  • @PanagiotisKanavos While being so active in criticizing other answers you could care to write your own which addresses the problem and includes all of your invaluable recommendations. – Fabjan Apr 14 '16 at 10:39
  • @Fabjan the answer was given from the first comment. Check the other answers to see what is a good answer for this question, especially Cetin Basoz 's answer. I suspect this answer will get many upvotes in the future – Panagiotis Kanavos Apr 14 '16 at 10:42

3 Answers3

3

Managed to figure this out.

var coll = database.GetCollection<BsonDocument>("Footballers");

        var documents = coll.Find(new BsonDocument()).ToList();
        for(int i=0; i<documents.Count(); i++){
            Console.WriteLine(documents[i]);
        }
        Console.ReadLine();

Applied a simple for loop for the documents variable and printed everything as intended.

Kelb56
  • 587
  • 3
  • 8
  • 21
1

2.x API use Async methods. You can use the 1.x API but probably you wouldn't want to.

There are basically 3 ways to retrieve the data: ToListAsync()

var list = await col.Find(new BsonDocument()).ToListAsync();
foreach (var doc in list)
{
    Console.WriteLine (doc.ToJson());
}

ForEachAsync()

await col.Find(new BsonDocument())
    .ForEachAsync((doc,i) => { 
      Console.WriteLine ("Doc #{0}:{1}",i,doc);
    });

ToCursorAsync()

using (var cursor = await col.Find(new BsonDocument()).ToCursorAsync())
{
 while (await cursor.MoveNextAsync())
 {
  foreach (var doc in cursor.Current)
  {
    Console.WriteLine (doc.ToJson());
  }
 }
}

Here the last one ToCursorAsync use a cursor and I think it is the one you would like to have on a web page. Instead of retrieving the whole data you fetch blocks of data.

Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39
-1

Get you result in GenericRecord like

IEnumerable globalRelordList = MongoClient.GetDatabase("football");

Code:

char[] commaSeperated = new char[] { ',' };
string[] auditRecordJSON = G.Data.Split(commaSeperated, 2);
auditRecordDTO audit = (jsonParser.JsonDeserialize<AuditRecord>("{" +auditRecordJSON[1]));

Your GenericRecord class have this property:

public class GenericRecord{}
{   public string Id { get; set; }
    public string Data { get; set; }
    public string CollectionName { get; set; }
    public RecordFormat Format { get; set; }
}

here auditRecordDTO is C# DTO which has same JSON field as your DTO.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236