Retrieving the data from the MongoDB using C# is pretty simple and there are three different ways the data can be rolled out for frontend
List
Cursor
linq
1.List
data
{
"_id": { "$oid":"56d5f7eb604eb380b0d8d8ce" },
"student_id":{ "$numberDouble": "0" },
"scores":[
{"type":"exam","score": {"$numberDouble": "78.40446309504266" }},
{"type":"quiz","score": {"$numberDouble": "73.36224783231339" }},
{"type":"homework","score": {"$numberDouble": "46.980982486720535" }},
{"type":"homework","score": {"$numberDouble": "76.67556138656222" }}
],
"class_id":{"$numberDouble": "339"}
}
var documents = collection.Find(new BsonDocument()).ToList();
foreach(BsonDocument doc in documents)
{
Console.WriteLine(doc.ToString());
}
//filtering on documents in which inside the scores array there is an exam subdocument with a score value greater than or equal to 95.
var highExamScoreFilter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>(
"scores", new BsonDocument { { "type", "exam" },
{ "score", new BsonDocument { { "$gte", 95 } } }
});
var highExamScores = collection.Find(highExamScoreFilter).ToList();
2.linq
//c#同步变异步的写法
public virtual async Task<IList<Article>> GetAllArticleAsync()
{
var query = _articleRepository.Table;
// query = query.OrderByDescending(b => b.CreatedOnUtc);
var factory = Task<IList<Article>>.Factory;
var result = await factory.StartNew(() => query.ToList(), System.Threading.CancellationToken.None);
return result;
}
3.Cursor
data
{
"_id": { "$oid":"56d5f7eb604eb380b0d8d8ce" },
"student_id":{ "$numberDouble": "0" },
"scores":[
{"type":"exam","score": {"$numberDouble": "78.40446309504266" }},
{"type":"quiz","score": {"$numberDouble": "73.36224783231339" }},
{"type":"homework","score": {"$numberDouble": "46.980982486720535" }},
{"type":"homework","score": {"$numberDouble": "76.67556138656222" }}
],
"class_id":{"$numberDouble": "339"}
}
filtering on documents in which inside the scores array there is an exam subdocument with a score value greater than or equal to 95.
//filtering on documents in which inside the scores array there is an exam subdocument with a score value greater than or equal to 95.
var highExamScoreFilter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>(
"scores", new BsonDocument { { "type", "exam" },
{ "score", new BsonDocument { { "$gte", 95 } } }
});
var cursor = collection.Find(highExamScoreFilter).ToCursor();
foreach (var document in cursor.ToEnumerable())
{
Console.WriteLine(document);
}
using (var cursor = await col.Find(new BsonDocument()).ToCursorAsync())
{
while (await cursor.MoveNextAsync())
{
foreach (var doc in cursor.Current)
{
Console.WriteLine(doc);
}
}
}
Referrence http://stackoverflow.com/questions/6772261/retrieve-data-from-mongodb-using-c-sharp-driver.