Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using MongoDB.Bson;
- using MongoDB.Driver;
- namespace MongoDBCRUDExample
- {
- class Program
- {
- static void Main(string[] args)
- {
- MongoClient dbClient = new MongoClient(<<YOUR ATLAS CONNECTION STRING>>);
- var dbList = dbClient.ListDatabases().ToList();
- Console.WriteLine("The list of databases on this server is: ");
- foreach (var db in dbList)
- {
- Console.WriteLine(db);
- }
- Console.WriteLine("Connecting to sample_training.grades");
- var database = dbClient.GetDatabase("sample_training");
- var collection = database.GetCollection<BsonDocument>("grades");
- // Define a new student for the grade book.
- var document = new BsonDocument
- {
- { "student_id", 10000 },
- { "scores", new BsonArray
- {
- new BsonDocument{ {"type", "exam"}, {"score", 88.12334193287023 } },
- new BsonDocument{ {"type", "quiz"}, {"score", 74.92381029342834 } },
- new BsonDocument{ {"type", "homework"}, {"score", 89.97929384290324 } },
- new BsonDocument{ {"type", "homework"}, {"score", 82.12931030513218 } }
- }
- },
- { "class_id", 480}
- };
- // Insert the new student grade records into the database.
- Console.WriteLine("Inserting Document");
- collection.InsertOne(document);
- Console.WriteLine("Document Inserted.\n");
- // Find student 10000 in the database and print the record
- Console.WriteLine("\n**********\n");
- var filter = Builders<BsonDocument>.Filter.Eq("student_id", 10000);
- var foundDocument = collection.Find(filter).First();
- Console.WriteLine("Found the following document: \n");
- Console.WriteLine(foundDocument);
- Console.WriteLine("\n**********\n");
- // Find all records with class_id above 400, sort them in descedning order
- // iterate over them and print them out.
- Console.WriteLine("List of students in a class with id 400 or higher: \n\n");
- var quizFilter = Builders<BsonDocument>.Filter.Gte("class_id", 400);
- var sort = Builders<BsonDocument>.Sort.Descending("student_id");
- var cursor = collection.Find(quizFilter).Sort(sort).ToCursor();
- foreach (var student in cursor.ToEnumerable())
- {
- Console.WriteLine(student);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement