|
| 1 | +using MongoDB.Driver; |
| 2 | +using System; |
| 3 | + |
| 4 | +namespace Kritner.MongoDb.GettingStarted.ConsoleApp |
| 5 | +{ |
| 6 | + public class MyHelloWorldMongoThing |
| 7 | + { |
| 8 | + public DateTime DateCreated { get; set; } = DateTime.Now; |
| 9 | + public string MyDatas { get; set; } |
| 10 | + } |
| 11 | + |
| 12 | + class Program |
| 13 | + { |
| 14 | + static void Main(string[] args) |
| 15 | + { |
| 16 | + Console.WriteLine("What would you like to enter for MyDatas?"); |
| 17 | + |
| 18 | + // Get some input from user |
| 19 | + var myDatas = Console.ReadLine(); |
| 20 | + |
| 21 | + // Create an object with the data that was entered |
| 22 | + var obj = new MyHelloWorldMongoThing() |
| 23 | + { |
| 24 | + MyDatas = myDatas |
| 25 | + }; |
| 26 | + |
| 27 | + // get a mongoclient using the default connection string |
| 28 | + var mongo = new MongoClient(); |
| 29 | + |
| 30 | + // get (and create if doesn't exist) a database from the mongoclient |
| 31 | + var db = mongo.GetDatabase("MyHelloWorldDb"); |
| 32 | + |
| 33 | + // get a collection of MyHelloWorldMongoThings (and create if it doesn't exist) |
| 34 | + var collection = db.GetCollection<MyHelloWorldMongoThing>("myHelloWorldCollection"); |
| 35 | + |
| 36 | + // Count the items in the collection prior to insert |
| 37 | + // Using an empty filter so that everything is considered in the filter. |
| 38 | + var count = collection.CountDocuments(new FilterDefinitionBuilder<MyHelloWorldMongoThing>().Empty); |
| 39 | + Console.WriteLine($"Number of items in the collection before insert: {count}"); |
| 40 | + |
| 41 | + // Add the entered item to the collection |
| 42 | + collection.InsertOne(obj); |
| 43 | + |
| 44 | + // Count the items in the collection post insert |
| 45 | + count = collection.CountDocuments(new FilterDefinitionBuilder<MyHelloWorldMongoThing>().Empty); |
| 46 | + Console.WriteLine($"Number of items in the collection after insert: {count}"); |
| 47 | + } |
| 48 | + } |
| 49 | +} |
0 commit comments