Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. using System;
  2. using MongoDB.Bson;
  3. using MongoDB.Driver;
  4.  
  5. namespace MongoDBCRUDExample
  6. {
  7.  
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. MongoClient dbClient = new MongoClient(<<YOUR ATLAS CONNECTION STRING>>);
  13. var dbList = dbClient.ListDatabases().ToList();
  14.  
  15. Console.WriteLine("The list of databases on this server is: ");
  16. foreach (var db in dbList)
  17. {
  18. Console.WriteLine(db);
  19. }
  20.  
  21. Console.WriteLine("Connecting to sample_training.grades");
  22.  
  23. var database = dbClient.GetDatabase("sample_training");
  24. var collection = database.GetCollection<BsonDocument>("grades");
  25.  
  26. // Define a new student for the grade book.
  27.  
  28. var document = new BsonDocument
  29. {
  30. { "student_id", 10000 },
  31. { "scores", new BsonArray
  32. {
  33. new BsonDocument{ {"type", "exam"}, {"score", 88.12334193287023 } },
  34. new BsonDocument{ {"type", "quiz"}, {"score", 74.92381029342834 } },
  35. new BsonDocument{ {"type", "homework"}, {"score", 89.97929384290324 } },
  36. new BsonDocument{ {"type", "homework"}, {"score", 82.12931030513218 } }
  37. }
  38. },
  39. { "class_id", 480}
  40. };
  41.  
  42. // Insert the new student grade records into the database.
  43.  
  44. Console.WriteLine("Inserting Document");
  45. collection.InsertOne(document);
  46. Console.WriteLine("Document Inserted.\n");
  47.  
  48. // Find student 10000 in the database and print the record
  49.  
  50. Console.WriteLine("\n**********\n");
  51. var filter = Builders<BsonDocument>.Filter.Eq("student_id", 10000);
  52. var foundDocument = collection.Find(filter).First();
  53. Console.WriteLine("Found the following document: \n");
  54. Console.WriteLine(foundDocument);
  55. Console.WriteLine("\n**********\n");
  56.  
  57. // Find all records with class_id above 400, sort them in descedning order
  58. // iterate over them and print them out.
  59.  
  60. Console.WriteLine("List of students in a class with id 400 or higher: \n\n");
  61.  
  62. var quizFilter = Builders<BsonDocument>.Filter.Gte("class_id", 400);
  63. var sort = Builders<BsonDocument>.Sort.Descending("student_id");
  64. var cursor = collection.Find(quizFilter).Sort(sort).ToCursor();
  65. foreach (var student in cursor.ToEnumerable())
  66. {
  67. Console.WriteLine(student);
  68. }
  69.  
  70. }
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement