Kelb56
Kelb56

Reputation: 657

Retrieve collection of objects

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.

Upvotes: 4

Views: 621

Answers (3)

Cetin Basoz
Cetin Basoz

Reputation: 23797

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.

Upvotes: 1

Kelb56
Kelb56

Reputation: 657

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.

Upvotes: 3

Chirag Kavathiya
Chirag Kavathiya

Reputation: 24

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.

Upvotes: -1

Related Questions