How to Connect MongoDB to C# the Easy Way

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
mongodb can be an extremely powerful database choice as well as an incredibly simple database to set up but how easy is it to talk to mongodb from c sharp it turns out the answer is very easy in this video i'm going to start by showing you just how easy it is to connect c-sharp to mongodb we will read and write data to a new database within just a few minutes then i'm going to take you deeper to cover the major operations you will need in the real world including querying inserting updating deleting and even transactions and working with the cloud as you probably know i'm a big fan of mongodb that's why when they reached out to explore the possibility of a partnership i was thrilled to accept this video is sponsored by mongodb but there's a lot more to it than just a simple sponsorship mongodb wants to help the community and so do i so we put our heads together and came up with a plan we're gonna use the sponsorship dollars to fund a giveaway of six copies of my largest course but then since i want to help as well i'm gonna be matching the amount mongodb is giving away to bring the total copies to 12 copies but we aren't going to stop there mongodb and i are partnering to bring a new full course directly to youtube for free starting in january now mongodb makes a great product as you'll see in this video but they also make a great partner for the community i would encourage you to check out the link in the description where you can find out more about mongodb the first 10 people who sign up for atlas mongodb's cloud database option using my link and adding the code mkt dash corey that's down in the description at checkout we'll get an additional 100 in credits but either way you can use the free version of atlas for all of your testing needs so please take some time to thank mongodb for helping the community and follow them on twitter at mongodb for your chance to win a copy of my course later in december now as with most of my videos i create some source code and if you want a copy of my source code that link as well is down in the description all right let's jump right into the course so here we have visual studio i'm on 2022 we're going to create a new project and we're going to create a console app to start we'll probably stay the console after the most part the goal is to focus in on how we connect c-sharp to mongodb but here's the trick this will work regardless of what ui you choose with the exception of blazer web assembly as we know blaze webassembly needs an api to talk to a database but otherwise the rest of the project types so api mvc wpf win forms and all the rest they will all work the same exact way when talking to mongodb so the code today can work anywhere so let's create a console app we're going to call this mongodb demo and mongodb demo app we're going to use which is the current lts supported branch or current lts version which is long term support of dotnet we hit create and we'll get rid of the initial stuff that it creates for us we don't need that and now we're pretty much ready to go to start building our application now what we're going to do here is i'm going to first just connect to mongodb we're going to get started right away i want you to see very quickly how to connect and read and write data to a brand new database that way if that's all you're looking for you'll see that in the very beginning but if you want to go deeper i'll have that too so let's talk about compass when you install mongodb locally for testing you'll get compass encompass allows you to connect to your local database or to the cloud i actually have a connection for each of them locally so i can connect to my local database or my local databases actually this is a local server or my cloud server on atlas let's start with the local database notice it's localhost with a port of 27017 that's the default we'll hit connect and here you can see i have a bunch of just test databases that are set up we're not going to create a new one okay we're not going to create a new one through compass we're going to do it right through code so you can see how easy it is so right now we have task suggestion app testdb testing local demo config admin this just means i've been doing a lot of testing with mongodb and playing around with it recently i just reinstalled on my computer after having upgraded my computer so with all of this notice that we don't have a database called simpledb that's the one we're going to use today so there's no simple db database all right let's go back over to our code and if you want start the timer it's only a few minutes to get going the first thing to do right click on dependencies say manage nuget packages you're going to search for mongodb.driver and this one right here mongodb.driver is all you need to install in order to talk to mongodb now if you're not familiar mongodb is a document database it's different than sql server we're going to deal with documents instead of dealing with tables it is a different philosophy we'll get more into that as we go deeper into this video but for now just note that it is different than sql okay i need two using statements first of all using mongodb.driver and then we're going to add another class in here so i want to using for mongodb demo app which doesn't exist yet that namespace no worries we're going to right click and say add new class and recall this the person model and i'm going to change this over to use using quick actions refactoring the file scope namespace i just like that a little better so with this let's make this public and we're going to add three properties in here a string id non-int a string first name and if you notice i'm using prop that's a snippet that allows you to quickly create an auto property string last name so that gives me my three properties this is just a very very simple setup for testing out how we're going to read and write now up here above my int i want to add two decorators first bson id now ctrl dot to add that using statement the top and second of all i want to add a b sign representation for vsan type dot object id now we can shrink this down by just doing this and have a using statement at the top so let's just control dot there and add that using so now we have two usings up here we have one for mongodb.bson and one for mongodb.bson.serialization.com now what's going on here well i'm decorating this model to say that this right here is my unique identifier now in sql we have the auto incrementing value that we use an integer for traditionally for our id in a document database it's a little different and part of the reason why is because a document database is designed to be used around the world with synchronizing databases and it's a lot more complex in some ways but in some ways it's a lot simpler because we can use a id that's an auto-generated id that's unique across the world and then with that we can create have multiple databases that are taking in new data all the time without having to keep track of oh i gave number one to that database number two to that database oops i have a number three on both databases that are being inserted that's a problem not to worry with this id it's a globally unique id based upon basically the probabilities okay so in very very small chances there might be a repeat but probably not and probably not i mean like billions of chances um so with this it's going to create an auto id of and it's going to say hey this is an object id now when the this data gets stored in mongodb is technically stored what's called bson which is like json but binary and so we say hey this is a bson id saying this is the identifier for this record the cool thing about document database is that you don't have to have a given structure for a document you can put different documents in the same collection and it can be okay now typically don't do that at least not radically different documents but with this we're saying here is the structure of my object and by the way this right here is the unique identifier for the record okay so that's all that decorator does it will take care of putting the id in for us we don't have to generate that id if we don't want with that we can go back to our program.cs and now we should have mongodb demo oh you know what i put app at the end of that there we go that's the right using statement now so with those two things we now need to connect to our database normally i would use a appsettings.json but because we're moving quickly on this let's just say string connection string and we'll put our connection string in here for mongodb colon slashes 127.0.0.1 [Music] and then our our port number 27017. and again this is pretty standard so that's our connection string again i would use appstage.json to pull that normally but for a simple demo we can just put it right here hardcoded string database name equals simple db remember that's not created yet and then string collection name equals let's go with people okay so now we can say var client equals new client actually there we go it auto completes for me var db equals client dot get database and there's the database name var collection equals db.getcollection and we'll pass a collection name but where i give a type person model so we've done here is we've got a connection to mongodb using that connection string we've connected to our database which again does not exist so the list of database names doesn't exist yet that's okay then we're going to talk to a collection think of a collection somewhat like a table in sql it's different but it's similar it's going to hold a set of data that has a relationship to each other so now var person equals new person model and we'll just fill in first name equals tim and last name equals corey okay real simple now await collection dot insert one async person guess what we are now done we have written something to mongodb now i haven't run this yet so it's not actually perform that action but that's it for talking to mongodb we have to set up our connection which database we want to talk to which collection we want to talk to and then just say insert one async and it will insert this record which we just created now just inserting records not quite good enough for me let's say var results equals a weight db i'm sorry await collection dot find async so i'll find something and this is a little bit of an interesting syntax but what we're saying is we're going to pass in the the query what things you want to look for what's the the filter criteria which we don't have any so we're going to say is this is the discard character meaning i don't care what this variable name is i'm not going to use it but i want you to return a record where true is true which means basically return every record that's what find async is going to do is going to say okay here's the here's the criteria for filtering oh every record that's it okay so we'll return every record and let's do a for each var result in results dot to list let's make that into a list and then from here we can say console.writeline that's our string interpolation we'll have result.id we'll put a colon space result.firstname space result.lastname that'll be it that's our entire application it fits in 21 lines of code if you take out this extra space up here 21 lines of code that read i'm sorry inserts into a database that actually gets created as we do and then it reads out of it the values let's see an action there we go so it says here's the id and then here's the name if you go to compass and we refresh we'll see we now have a simple db database inside there's one collection inside there's one object id that's our id field and the first name is tim and the last name is corey just to prove this is really the case and let's see if we can't zoom in here a little bit that's a little small i can double click here and i can modify this to say timothy now we didn't do that in the code we did that in the database and again every time we run this code it's going to insert a record so let's run this again and now i can see a different id one says timothy 1 says tim so now we can see that we are inserting the database and we're reading back out of it that's really how easy it is to talk to mongodb but we're gonna make it even more clear as we expand into all the things you really need because probably you're thinking okay i can do inserts and i can do reads what updates what deletes or you're asking for every record how do i filter and what if i need to insert into more than one collection which by the way isn't something you should be doing very often we'll get to that in a little bit but i can see all those questions i've heard all those questions and i'm going to show you how to go even deeper so that's our initial demo you can see how to connect to mongodb but we're going to go even deeper and look at all the options you could do with mongodb now do this well and not waste your time i'm going to do is i'm going to copy and paste just a little bit of code just for models so let's create a new class library so we'll create a class library it'll be a net six class library we're gonna call this data access and yes.net six in here we'll delete class one and we're going to create let's try and set this up mostly correct so data access this is a demo but at the same time i do like to have my demos be actually workable code so let's create a actually before we do this let's create a new folder called models and in here i'm going to create a user model well you know what i'm going to show you something really quick we're going to on the solution right click and say add let's get the editor config in here that way just close it out and reopen it it for some reason doesn't open the first time change the code styles and go to file scoped that's it so now once that gets applied this would create forest file scope models we're going to create the user model here and it didn't the first time it does this once in a while where it doesn't set it up correctly at first but then it will update so mark this as public and here is my code let's install the mongodb package not mongodb.bson though we want to go back to manage nuget packages mongodb.driver and install this now there is no way of doing this i'll hit install here but since we already had it in the other project which by the way we don't have to if we just call this class library but since we have it already there then what we could do is we could go to our project and see us right here this item group where it says mongodb.driver in package reference we could copy this whole thing come over here and paste it in here and that would just apply that nuget package as well it'd be a shortcut okay so there's our user model id first name last name and full name is just a first and last name put together that's a read-only property so that's our first model our second model is going to be a chore model and there you go see that the um filescope namespace worked that time and in here make this public we're going to again i'll grab and copy from my other project and paste it in here just because you don't need to see me retype all this stuff this is the and notice i added the using statements because it now has that package therefore it knows where they came from but id chore text frequency and days assigned to and last completed so it's a little demo i built we're not gonna do the whole demo we're just going to do the mongodb and data access side of things but what this does is it's it's a chore system so if you have chores on the house if you have kids that have chores as well maybe you're splitting up the duties in the household you can say okay i need to mow a lawn every seven days you put that in a list under your name and then what will happen is we will track when it gets done you'll say yes i just did this or hey this one's due let's go ahead and do that chore so it's a nice little tracker that works for multiple people so you can track not just yourself but yourself your kids your spouse your whole family if you want so that is the chore model and the last one is going to be the chore history model copy that code and then come over here and say add new class chore history model make it public i'll get rid of the using system usings that we don't need we'll paste in that code again it's going to add those two additional usings and now we have id chore id we have the chore text date completed and who completed i also have two constructors here one that's the normal blank constructor that's just empty but then one that takes in a chore model so you pass in a chore model and it says okay let's create a history event for that chore so we will update the when the chore was last done and we'll update who is assigned or we grab who it's assigned to and the text and we'll create a model off of that that way we can very easily create a history entry when we update the chore saying yes i just just completed this so those are the models let's close this down and we'll close this one as well so those are the models for our new demo and now we're going to do is we're going to create some data access we're going to create a class let's call this um let's call this just chore data access we can get a lot more specific here and make this um work with both you know sql and nosql mongodb by the way is a nosql database but we're just going to focus in on making this a mongodb database so we will add a using up here for let's go with it's called db data access dot models that we have access to those models and we also need the using for mongodb dot driver that'll be for accessing mongodb stuff now up top what we're going to do is we're going to create a few constants for our our different things like for example our database name our connection information and so on so private const string and this will be the connection string and again we would normally pass this in so normally we would grab this from a eye configuration but we're going to hardco it just for sake of simplicity and so for now we'll grab that from over here let's copy it paste it in there is our first cons i'm using const because they're a little more efficient when it comes to memory usage we're not going to change these values these are just putting them up top so that they never change and we can reference them multiple times if we do need to change the value you can change it in one spot okay private const string database name and we'll call this our chore db let's make sure there's no chore database already in our list let's go back to our databases and look and there's no chores admin let's zoom in here admin config demo local simple db and so on no chore db so short db it is and then private const string let's say the chore collection equals chore chart this is remember collections are kind of like tables private cons string user collection equals let's call it users and private const string sure history collection sure history okay so now we now have three different collections we can talk to again we have not created these in the database we haven't even created a database that's okay the first time we use a database if it doesn't already exist it will get created that's the difference between uh sql and a nosql database like mongodb where we don't have to have all this confusing or con set up beforehand no configuration sql statements t sql all the declarations of what should be where don't need it all we need to do essentially is say hey here's data this is where it should go if it doesn't exist create it and the cool thing is when we passed in that person model it just created a person object for us and put it into the table it created a structure for us so we come over here and we want the chore collection or the users or the chore history no problem it'll create those three collections for us and put data in those collections that we give it when it comes back out it comes right back out in the same structure it's very very easy there's no translations to it okay so now notice that in program.cs we have this setup and we have to do this setup for every collection so instead of doing that every single time in every single call i'm going to create a private i collection of type t called connect to type t in string collection now this is some advanced stuff we're using generics here we're also using a little used keyword called in now in was was added in c sharp 7.2 i believe it's kind of like ref where it passes a reference but the difference is we cannot modify it once we pass it in so what we're going to do is we're going to use this to pass in our constants that way we're not creating a copy of them we're not allow them to be changed it will be just a little bit more efficient you don't have to do this you could leave off the end it would still work but this is a little bit of an efficiency boost for us and with strings the more efficiency you can have the better since they're pretty inefficient objects now the generics what we're saying is we're going to pass in a type and what i want to get back is a collection of that type so this allows us notice who passed in right here person model for the collection we're going to pass in that type and get back a collection of that type now we can pass in three different ones shore history model shore model and user model and get back the connection for each of those so var client equals new client and we're going to pass in our connection string that's the um the constant and then we're gonna say var db equals client dot data of type database name we're going to assume we're only using one database here not multiple databases which is most common just to use one database return db.get collection of type t passing in collection so we're going to pass in this name which is either chore chart users or chore history where i get that collection and it's going to be of that type okay so that's our our set up we're going to do over and over and over again we can just do once now in one private method now let's create some connections or talk to mongodb so private async we'll make everything async task of type list of user model so return back a user model and we'll say get all users like so and then in here we'll say var users collection equals connect to of type user model and pass in user collection so that's now this line right here represents these three lines of work so one line is what we've done we reduce it to and then we have var results equals a weight user collection dot find async and again we're going to say i want you to find all of them so there is it's a get all therefore we don't have to filter this in any way return results dot to list that's our get all that method right there gets all the users now let's keep going we've already seen that once so let's do some more public async task list of chore model get all chores and it's essentially the same thing as this let's copy and paste but this time it's going to be short model and we're going to pass in the chore collection like so and we should say chores this is why copying and pasting isn't always the best option but it's essentially the same thing okay it's the same pattern it's just now for all chores and we'll we'll stop there in the get all we don't have to do every method here or every thing they would do in a normal database i just want to get to the main things so you can see the differences so how about public async task type list of chore model but this time we're going to do is get all chores for a user it'll pass in a user model user so it's going to filter our search so just like the chores up here we're gonna do something similar so let's copy and paste it that would be returning everything but we don't want to return everything so instead we're gonna say instead of this filter where everything is true going to say c instead of that discard character because we do want to see the model so c dot assigned to dot id equals user.id now what's going on here well this is going to say i want you to look up all the chores but filter them where the assigned to id is the id of the person is passed in so if we look at our models the chore model has assigned to and in that at the user model so in that we have an id so it's looking at a sub id it's looking inside of a collection instead of an object into its that obvious property so object sub-object property and comparing that to this value and saying hey if they match return those results so that's how you filter by some type of data in your model now let's go on let's look at inserting some records so public task create user user model user notice i'm just saying public task because i'm going to return this without awaiting it so var well user collection we can just grab that from up here that connection string looks the connection information looks the same the same every time so return user collection dot insert one async user that's it that's how we create a user let's do the same thing with a chore just we have both of these we can actually test this public task create chore shore model sure there's our chores collection return shores collection dot insert one async and again intel code starting to learn what i'm doing anticipate my my needs which is awesome next up let's do public task update sure sure model sure and in here again the chores collection but now we need to create a filter var filter equals builders for chore model dot filter oops dot eq for equals id chore dot id and that's saying okay we want to filter this where we're saying only update the record where the id matches this id so we're updating a record we're passing the whole record in including its id where i grab that id and say hey this is what we're going to update this record and since that's a unique identifier it will only update one record based upon this match it's gonna filter to only match the id they pass in now return chores collection dot replace one async we pass in the filter the chore and then we're gonna say new replace options is up search equals true that kind of scroll off the screen there we go so what that does is it's going to find that record it's going to say oh there's an update to it so we're going to replace the whole record so it's going to remove the old record put the new record in that's the update and then if it's not does not exist it's going to insert the record that's what an upsearch is it's either an update or an insert depending on what you need so this way even if it doesn't find it it's going to say oh well it should be there and if it's not no problem we'll just go ahead and insert it so why are we doing a full update why are we replacing the whole object instead of just the fields we need well because it's still super efficient this is not like sql where we have to go through and insert a whole bunch of update you know this table and this this spot and all that kind of stuff we just pull out a json document or bson technique let's json for what we see pull out a json record and put a new one in that's super efficient so it's actually more efficient just to do this than to try and figure out a way to update individual fields unless you know for certain which fields may be updated now with this i do not point out that mongodb is different than sql i want you to concentrate on that don't just bring your relational database ideas and try to apply them to a non-relational document database like mongodb this insert update what we've done is we pulled all the data down from mongodb we have made changes in c sharp we're going to put the whole record now back so this isn't going to lose data this is just going to update a record okay so that's how we do the update let's go on to delete public task delete chore now this is not something we often do but i did want to show it because in the event that you do have to delete something i want you to know how to do it okay so normally we just say mark it as archived or move it out into an archive or something like that but we are going to in this case delete a record so return chores collection dot delete one async where we say c arrow c dot id equals chore id so what this is doing is saying delete one record based upon the id of that record matching the id we're passing in we have the id for mature we're saying just match the id and just delete the record we don't have to pass the data in beyond that we're just saying these two match then you're good to go delete since that's a unique identifier that's all we have to do for delete so we now have a full crud access to mongodb we have creates with our inserts so that's what we're doing right here we create our users we have up we have reads which would be our get and get all so we have get all we also have get with a filter on it and then we have our update and we have our delete that's full crud access we can make these calls right from here so you can we can comment out most of this stuff and we can reference our our library so let's right-click on our project and actually whoops let's go to dependencies how about that and add project reference check the box for data access and now we can start referencing we just need to create a chore data access control dot to add that using let's call it db not data access db equals there we go and now we can start working with our chore data access now let's add a using up here for data access dot models now we could use the global using for this it depends i probably put the models in global using but that'd be about it so now we can say db.create user we can pass in a new user new user model and let's um let's say the first name equals tim and the last name equals corey like so i think that's all the the information we need for a user model first name last name yep that's it so we can create the user and let's just run that when we do it just says hey you can close the app now it's done we can come back over here refresh our databases and we'll see that what we call it the chore database that should show up here shortly if we named it right let's try reconnecting because i may have broken something okay localhost connect it's not showing up it may be i put in the wrong database let's find out let's go over here to the chores i call the name choredb of course this comes down to a dumb error on my part i did not mark these as asynchronous so i forgot to await now you could mark all these as async i prefer not to do that and just make everything async but it's really up to you and your preferences for if you want to mark things as async just a reminder that hey you need to await that call so let's try as again this time we will build we'll wait for it to to run same amount of time we'll come back over here to our databases we will refresh and now we have a chore db with a user table with one object in it that is tim corey cool so now we've got one user that we can then look up so we can say db dot get all users maybe get all users if not when you create one so yeah get all users ah we marked it as private i always watch the modifiers so public get all users so ctrl j here bring the list back up and now get all users and again we need to weight this so we're going to say home var users equals a weight get all users that's going to give us a list of user model and from there we can create a chore so varchar equals new chore model and we're going to say assigned to equals we're going to kind of cheat here just to get something going users dot first well just user dot first and that will grab the first user in our list of users from a database and the chore text equals mo the lawn let's unpin this and what else we need to add here frequency and days yeah every every one day is kind of excessive let's do every seven days like so and last completely we don't have one of those we're just going to say you know whenever so we haven't done it yet therefore it's not completed yet we can um let's bring this down here and and make us look a little better like so that way it's a little prettier and now we can say await db dot create chore and pass in that chore so now create a chore from that chore list and let's just run this it's going to create another tim cory that's okay it's already done so let's bring up our compass which i believe is closed that was a mistake no problem we will load compass back up you can see again how to log into compass grab your connection to your local host hit connect and in here we have our chore db we now have a chore chart and on here we can see that mulan frequency is days is seven assigned to is tim corey now you may notice that this has actually copied the data from my users table so i have an entry now in the users table called tim corey actually two of them now but i have in the assigned to i have tim corey as well and you may say oh that's duplication of data that's not dry that's that's a bad thing and it's not and here's why with sql server in all relational databases in general that includes mysql and sql lite and all the rest the relational data model is all about saving space it's about saying we're only going to write things to disk once and we're going to do that at the expense of time because it's going to we're going to break apart these things into their various parts and then link to them using ids so it comes time to write to a database you may have to write two three four five ten different locations at once because you have to write addresses to their own table and phone numbers their own table and email addresses their own table and the person record their own table and then link all those together whereas in a document database we store all of the information together as much as possible we do occasionally link out in fact there is the id here so we can create a link if we need to if there is additional information about that user we wanted to look up we could actually use that id to look up the user but we want the at least the information they're always going to want with the chore to be with the chore because non-relational databases no sql databases are going to focus more on speed data access speed the idea of how fast can we get you back the data that means we don't write to a a lot of different collections for one record we want to write to it ideally one object that's it we don't want to have collections all over that link to each other because that's inefficient now it does mean a duplication of data and we do have to know what is the the primary data well in this case assigned to has that object id so it's saying is this is not the primary record but i do know where that is if you wanted to update that way if later in the users section we updated tim's name at timothy we could in theory go back and update assigned to to reflect that new name now it was assigned to tim when tim was calling himself tim yes we could go through an update and we probably should but we don't have to if this is just for historical purposes then it's not necessarily necessary to do so but what this does is it allows me when i'm looking for just the information on a chore i get all the information all the linked information all in one spot with one call with no filtering i just have to say hey that's the record i want i get all the data about it that makes it much faster we are sacrificing disk space for speed that's the trade-off here when it comes to relational versus nowhere non-relation or document databases so there are benefits to relational databases there are benefits to nosql databases like mongodb which you choose does depend on a situation but just note you need to treat each the way they were designed not the same way if you treat them the same way you're going to get bad results so that's my little bit of soap box for today let's talk now about what if we wanted to add one more thing here right now we have the concept of chore history but when we write to the chore history we also want to update this this last completed field to not be null but that means updating two different things let's start by looking at one way we could do this all right so one we could do it is to say uh public and let's let's call this async task of complete chore and pass in the chore model so we're going to say hey when you're ready go ahead and pass in a chore we'll say that you've completed it and put it in the history so we're gonna say let's grab the chores collection and say var filter equals builders dot chore model i'm sorry builders angle bracket shore model dot filter dot eq and id and chore dot id so we're going to say hey i want you to find the the chore based upon its id and we're going to do an update so wait chores collection dot update 1 async i'm sorry replace one async we pass in our filter and our chore and we can do we can just do that um we can also do the is upsert but i think we're just doing an update of an existing chore so we should be good so but that's only part of it we've updated the chorus say hey here's the new chore information by the way that's going to have the new updated time to it hopefully but that's not it we now also need to do an insert so var shore history collection we haven't done this yet connect to chore history model and pass in the shore history collection thank you intellicode await your history collection dot insert one async new chore history model but the cool thing we can pass in chore and that will set up our our chore history remember that in our chore history model we have that constructor that takes in a short model and it builds a chore history entry off of it so that's how we could insert well actually update and insert but that may not be ideal because we already have two different collections what happens if we have an exception on this line well we wouldn't write the chore history we'd update the fact that chore was done recently but we wouldn't know by who or how because the chore history was not updated along with it so that's not ideal so what do we do well this is where we would bring in a transaction the problem is that locally we can't use transactions so in compass if i were to try to use a transaction that won't work because it got a stand-alone cluster for a transaction to work we need to have an actual cluster with three different databases mongodb is great about working in the cloud with multiple databases even spread out across geography so that we can have a really responsive database that is synchronized it takes care of setting up the primary version versus the backup versions and all the rest of that stuff but locally we just have one copy of our database so we don't have that redundancy so we can't do a transaction locally well this is where we can bring in atlas so atlas is the mongodb in the cloud now you can put atlas into aws you can put atlas into azure you can run atlas directly so it's up to you how you work with atlas notice down the links down below i have a link to sign up for atlas remember you get the first 10 people that use that coupon or that id code will get a hundred dollars of credit for atlas but there's also a free version of atlas that you can use during that signup process so you can have your own free version to test out these things so the first thing we're going to do is i'm going to connect to atlas and i'm going to run this same code just to show you that it does work but in order to do that i need to put my connection string up here and it's it does have a little bit of security in there and passing in a username and password so i'm going to do is i am going to not show you that even though technically it's locked down to my ip address i still want to not show you that just in case um there's any problems or gets out so i won't show it to you but i'm going to put it right here and then we're going to come back over to program.cs and run the same thing over again and we're going to look at my atlas installation so let's do that all right so i've now set up my connection to atlas let's go back over here we're going to create a new connection and we're going to connect to this time atlas so here's my atlas connection string notice it it puts stars in the place of my password i hit connect and now i'm connected in the cloud and i have four databases in the cloud right now let's move this off a screen we're going to run this app let it run and it's completed already let's go back over to atlas we'll refresh and now we have a fifth database called chore db inside there we have a chore chart with an assigned chore let's zoom in here so you can see it there's our moa launch or frequency seven days a sign of tim corey we have just that one user for tim corey so it has set up our database in the cloud our two collections and now we're all set so now we do is work on making this chore or complete shore to be transactional i'm going to comment this out this will work but it's not transactional so again if you crash halfway through you'll lose your consistency so i don't like that i and ideally we would have a transaction but again i'd want to stress this very very clearly just because you can do transactions in the cloud does not mean that you need to think about databases in mongodb the same way you do as sql if you're doing lots of transactions you're probably doing it wrong i hesitate to even show transactions because there is a a idea that we want to abuse this and use transactions the same way we do with sql but there are times when transactions are necessary in those cases i want you to know how to do it but just note you you shouldn't be using transactions for most things so var client equals new client and we're going to grab that connection string now note that i'm not using my connect to setup that's because we need to start a connection and then we need to set up a using statement where we say var i'm sorry just using var session equals await client dot start session async so this is a using so that means that once we get to this end curly brace it will for sure close out of this session that's what we need to do and then we just start with our let's scroll up a little bit our session dot start transaction now if you're not from the transactions what happens is a transaction is an all or nothing thing if you are doing two different actions in two different collections and you need to make sure that both things happen then you use a transaction think of this like using a bank account here's a classic example if you are withdrawing 100 from your savings account and putting that 100 into your checking account you want to make sure that both actions happen if you withdrew 100 from your savings account but then the application crashed you would just lose a hundred dollars you want to make sure the second half works otherwise don't do the first half so the same thing is true here we're going to start a transaction and if everything goes well we're going to say go ahead and commit that transaction but if any error happens along the way we're going to say no no no roll back everything so when you try catch and we'll grab the exception and we are going to remove the the throw for now so inside of this try catch we can say var db equals client.getdatabase database name oops and then we say var chores collection equals db dot get collection chore model chores or chore collection there we go so it's going to connect to our chore collection and we're going to do basically the same thing here that filter and a weight let's just copy and paste those things in so we're essentially doing this these tasks up here but wrapped in a try catch with the session and we're also doing manually connecting to our our database in our collection all right so we're doing our filter we're doing our replace and then down here we're going to say varchar history collection equals db dot get collection sure history model and then the chore history collection and then await sure history collection dot insert one async new sure history model and we're gonna pass in the chore again it's gonna create it for us now at the very end of this we can say await this is very important session dot commit transaction async now that's the happy path the happy path is we connect to our database we create the session we start a transaction we update or replace our our chore we insert a new chore history entry and then we commit but what happens if we throw an exception anywhere in here well what we're going to do here is just say await session dot abort transaction async like so and we will do a console.writeline that says ex message just we can see the error message that's it we now have our our complete transaction so we have our start transaction we have our commit transaction and we have our abort transaction should anything go wrong with that we can now complete a chore so we've got a chore let's complete it so we can say await db dot complete chore passing that same chore so we're gonna create that new chore we're going to then um actually let's grab it back because this does not have the id on it so let's get rid of well we'll wait to get rid of that so we will say db dot get all chores and we'll say var chores equals await there we go don't forget the await and they can say chores dot first so complete the first chore in the list that's all we'll do let's run this and it's running it's done no errors let's go back to our compass where we can see we have let's refresh here we now have a chore history entry as well as on our chore chart we'll have um i'm sorry chor history chart we'll see who completed tim cory let's zoom in here tim corey completed mulan on this date and time so that now has taken care of our chore history what we didn't do was we didn't go in here and modify last completed we should have done that let's do that so we're going to grab that first chore let's um let's cut this out here and we'll say var new chore equals like so we'll say new chore dot last completed equals datetime.utc now just to be precise and we'll say complete chore so with that we'll run this again it's going to get already done by the time i open up my compass so let's go to chore history we now have two entries for mobile on we go back to the chore chart and notice that last completed is that date and i was assigned to tim corey it's mo lawn the chore history the same chore um we completed and we did it pretty close to one another so that's how you work with mongodb we've gone through the basics of it where we just you know kind of dabbled in just an insert and a read which was really really quick we could do that in a few minutes but we then went into this where we've got pretty much examples for anything you want to do if you want to do just get everything there's how you do that if you want to get with a filter by looking up and only getting certain records there's how you do it you want to do a create boom there's a couple options you want to update there's an option you want to delete there's an option you want to do transactions there's an option so what this gives you is not only a good demonstration of how to work with mongodb it also gives you a reference to go back to to say how is it again i do transactions or how is it that i do an insert or an update mongodb is a great option for working with the data in your c-sharp application as you saw working with the the cloud super simple you just have to have the connection string and then you connect right to it and there you go so it works just like it does locally so for testing purposes using the cloud is perfect and by the way i'm using the free version of atlas i'm not paying for atlas i don't have free credits for atlas i'm using the free version of atlas to do all of this so you can see that i actually have three different databases out there that are being replicated three different nodes so this is taken care of for me they update my databases in fact an update is coming in february of 2022 to 5. so that'll happen for me it's all taken care of it just works so i encourage you to check out mongodb see how it works for yourself sign up for atlas use that link down below it really helps make sure that people know they that you came from me that helps me and it helps say yes this was good to help the community and that's what we want to encourage here is mongodb is being a great community servant they're really helping out the community not just saying pay us now they are a business they do want to make money that's great that's fine but they are helping the community and they're helping us get started without having to have a big bill to work with so i would encourage you sign up for atlas using that link tell them thank you watch the app mongodb twitter handle for that giveaway over the month of december and then coming up in january even more cool stuff as they help pay for bringing a paid course over to youtube for free so you can learn much more about how to build a complete working production application using mongodb so again tell them thanks thanks to them for sponsoring this video and i hope you've learned a lot about mongodb trust me i would not show this off if i didn't believe in it if you go back and look i already have mongodb content on this channel it's already in my courses because it is a great option all right let me know what you think down below tell them thanks down below in the comments as well i appreciate you watching and as always i am tim cory [Music] [Applause] [Music] you
Info
Channel: IAmTimCorey
Views: 7,953
Rating: undefined out of 5
Keywords: mongodb, c#, connecting c# to mongodb, mongodb atlas, nuget, crud, nosql, cloud database, azure, aws, tim corey, iamtimcorey, timcorey mongodb, timcorey c#, data access, tim corey async, async
Id: exXavNOqaVo
Channel Id: undefined
Length: 70min 17sec (4217 seconds)
Published: Mon Dec 06 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.