MongoDb Basics | Vinod Kumar | Skillshare
Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
20 Lessons (1h)
    • 1. Introduction

    • 2. Overview of Mongodb

    • 3. Installation

    • 4. Inserting documents

    • 5. Importing data

    • 6. Executing scripts

    • 7. save() v:s insert()

    • 8. Projection

    • 9. Selection

    • 10. More queries

    • 11. $and $or $in Operators

    • 12. $where operator

    • 13. Aggregation

    • 14. The mapReduce function

    • 15. Indexes

    • 16. Updating documents

    • 17. The upsert operation

    • 18. Updating multiple documents

    • 19. Removing documents

    • 20. Thank you


About This Class

Mongodb is a one of the most popular NO-SQL database management system today. As against the traditional RDBMS, it stores the data in an unnormalized way, in binary JSON format.

Mongodb is an open source document database. The name is derived from Humongous DB. This falls into the category of NO-SQL databases. The data in Mongodb is stored in an un-normalized format, as a collection of documents. A collection in Mongodb is equivalent of a table in RDBMS and a document is equivalent of a record. However, unlike a record, a document need not have the same structure as other documents in the same collection.


1. Introduction: Hello and welcome to the Shark Coast on Mongo db fundamentals. My name is we know the end. I'll be your instructor for this course. I'm a full time self to a trainer, developer and consultant. Mongo DB is an exciting alternative to the good old Ali BMS on. In this course, I will show you everything you need to know as a software developer in order to get started with any mongo DB applications. In this course, you will learn many things right from insulation off mongo db on your machine to performing Currid operations writing simple to complex Clary's on much more. So let's dive in on start among would be fundamental straining. 2. Overview of Mongodb: Mongo DB is one of the most popular no SQL database management systems today. No SQL sent for not only SQL. The name Mongo DB is direct from humongous TV. As against the traditional arguments, it stores the data in an unknown blessed way in a former Caldas Beason, which turned for binary Jason in 2007 s after Chemical Engine began developing Mongo DB. And in 2009 the company shifted to an open source development model, with the company offering some commercial support. Onda some other services among good DVD device contains data in the form off one or more collections. Collections are equal into tables in an R D B. M s. What do you call it? Accord are growing and arguments here it's called as a document. Unlike reports of a table with share similar column structures, documents of among would be be collection may contain different structure. The document, simply put, is a bunch off one or more key value pairs. The keys can be called US properties or freeze as well. Here is an example of a valid Mongo DB document. As you can see, name and email are two fields. Andi corresponding to that. There are some string values. Here's another example off to documents being part of a single collection, nor that they both have some fields in common on DSA. Um different internally mongrel in the stores. These documents in Beeson format, which stands for bind marriages on As I mentioned earlier, a document is a group of field value piers. Fields are equal int off columns in a table value of field. Maybe string number Boolean arrays are even another object. Each document of a manga TV collection must have an underscore 80 field. And if you don't provide one mongo DB itself, Alassane on art originated value off the type called Objectivity. A collection in a manga TV database has a dynamic schema, such that the documents in the same collection may have different structures in arguments. Joints are expensive, and hence in Mongolia be they're not supported. Acquiring manga TV operates only on a single collection. Mongol David does not support transactions, either each entered update deal it individually, are transactional in nature. On this is because all related data are stored in a single document and there is no need to use multiple inserts. Update delete operations at all. Unlike our Deb Amos, data duplication is encouraged here so that all related data is in the same document, alighting unnecessary joins and step qualities. 3. Installation: in order to install Mongo db on your Windows machine. First, don't load appropriate installer, so that's good. A mongo db dot com and in the home page on the top, right corner somewhere you'll see here that there is a download link. Let's kick that, and that gives us few options. Andi, I would like to go with the communities there were and in the community server. Since we're using with those mission here, we have a couple of options, and the one that is shown by default is the one that we want to install. Let's like the dongle butter. The don't load will take a few seconds. It's another. The doughnut is done, so let's open the folder. And here is the installer. So let's go and double click that and complete the Wizard by choosing the most appropriate options by default. It has been installed in See Dr Program files Long would be Server 3.4, so they're the location and in the BIN directory will see some applications are executable . The one executable that we're interested right now is the Mongo D, which is a sort of our process. There is also claimed application So one thing is, you can just double click this Mondo Di, but it fails to start that because it looks for a folder called data slash db. In your Cedric, I don't have this folder ends when we run this weekend supply and ultimate folder way Mongo DB will use that as a temporary folder. So, you know, testes, Let's open a command front and then did the command mongo D with probably destined abortion on it gives me another saying that mongo D is not recognized as an internal or external. Come here to make this munger de command available on on command fronts were to add this folder location to our part environment variable. So I'm gonna copy that and then a right click this PC properties at once. System settings, environment, variables. Andi, I can are either here, but I can up into an existing part. You're so it's going out a new environment variable called Fought on base. That location that we copied once they said Okay. Okay on. Okay, it's with all the windows. And then I opened a new command prompt. Take the same command mongo de their stash watchin on. We get this Washington, which means you're successfully installed the Mongol Devi's after the next step is to create a data folder for Mongol Devi. So I'm gonna open, say, Dr Uncleared, a new folder. Now the name can be anything. Have you mongo db Dutch data. And then I can use this part when I run the server to run the server, issue this command from any command front now, which is mongo D best BB Pot sequel in mongo DB Ducks later. You can also optionally change the port numbers are the location off the server, etcetera. But I would like to live it to the default on a presenter. It starts the server, and you can see that there is a message that comes up waiting for connections on portal 7017 Now that happens to get the default report number. If you got this cream, that means you're mongo DB Insulation is successful and it has been started. No, let's minimize this and open a new command front. This time. I want to connect to the server using among go client, and then check if I can issue some commands. For example, I take mongo on impressed Ender, and you will see that it connects toe A Server six is connecting to mongo db slash slash 1 27 001 which means the local host and then the porters to 7017 which is where our Mongo DB is running. Through this command prompt, I can issue some mongo DB specific commands. For example, Show de BCE will give you the list of databases that have been created Andi visible. Now I can create a new DB by just typing. Use for example testily be now it's a switch to the TV test baby. However, if I against a show de BCE, it will not be listed because it doesn't contain anything so it gets lazily created, which means only when you add some data into your database, the database comes to existence, so we can also assure command called a DB to check what is the name of the baby. And it says that the current database is tested et on a recommend that can be used at this time is show collections. Now, since this DVD is empty, there are no collections at all. However, we can add a new collection on reissue. All these comments to see a different result. So let's get a new collection by adding a new document to that. And it's very simple. Just how today db dot on imaginary collection name, for example. I can say contacts, dart, insert, and then I can pass on a J phone document. So with the name value picks, for example, I can say name. We know female. We know that we know Dark seal. No. If I complete this, you'll see that it is right. Result number of records inserted. Here's one. And if I know issue the commands, show DVDs, you'll see that there the new database called testily be. If I also say show collections, I can't see my collection, which is the contacts and no to see the data which is stored in the context. I have to assure command db dot contact. Start find one. You can observe that there is another field inserted called Underscore 80 which has to be there for every document off any collection. Now the value for this can be user different also, but if you don't mention an object off a class called object, I d will be created. Onda. We will talk about this object early in the future lessons 4. Inserting documents: you know that we have created a contacts collection. We can also add arbitrary values. For example, I can clear the job was variable that there will be one equals to an empty object they will not name because toe Come on, they wondered. Email equals toe Come on at you know dot co we wondered City equals toe kangaroo. And now I can add this to the existing collection, which is contacts like until now, debido or contact, start, insert And then I can say the one and I will have a second record Now, in mongo db terminologies a record is termed as document and the reason is very simple. In arguments at a car consist off rows and columns where every role is off similar columns . But in case off mongo db, that's not so. Now if I say db dot context art find dot pretty you will see that there are two documents that exist with the different schema are different structure. And if you also have observed, we created the contacts collection without having to define a skim off that so this is one advantage off mongo db Are any no sequel? Databases engine you can also add a raise off objects. For example, if I can create war be underscored. Error equals toe on a day, which is like a square bracket. And then a cuddly record and then of a name is John Doe Onda and City is the last 2nd 1 Probably name is Gender City. That's in Chicago. Andi closed bracket. So no PR is in a hurry so I can check that out and the scenery and I liken entered this by using the same command again. So db dot contact start insult. And then I said, Be a are now, Since I given Ari, it's going to say that there are two documents that got inserted and it also gives me a different response this time that says that bulk a right result. There are no errors. Onda number off documents inserted is too, and some other useful information. Now I can just say here that d be dark Contact. Start find dot Pretty on. You'll see all the four documents are intact if you don't use the pretty function and then just I believe you got contacts. Start find you'll see that the output is not so pretty now this is true, especially if your document structure is very complex and nested and all the stuff the find function returns the cursor on. Since we're not collecting that, the Mongo shell displays the 1st 20 documents, and since we don't have enough documents, we're not seeing that of a difference. 5. Importing data: We can also import data from external fights that RCs we are. Yes, we are Jason Place. So Mongo DB comes up with a bunch of tools for these things. For example, if I go to the Mongol TV installation folder, there is a file called Mongo Import. Are dxy now the Mongol import, as the name suggest, Import a file into among body be collection off a particular date of it. So if I have to go to a client found and it's your command Mongol import pastors hope it would give me a bunch off options that I can use while importing. So it says Mongo import few options on and one file. The data can be represented. A CSP comma Separated values RTs three tab Separated values are Jason JavaScript Object notation format. We can also import. If the data is just a collection off mongo DB documents. We'll have a look into each one off this. I have a friend call Contact State or chase on on that contains 1000 contact information with similar fields. Now it is also possible in practice that the fields may really that we have already seen, but in this particular case, I have all of them off the same structure now. Another important is all I have to do is to come to the clan front Andi, then say Mongo import, and then I have to give a few options. The number one option is what kind off data that I have now I have a Jason Addy. The second important option that I might have to specify is the DB. In our case, it's called Test Devi, and in the best debated of is what is the name of the collection toe, which you want to import. If the collection named Very Hard Given is not available, it gets created. If it's already there, it's going toe on these documents into the existing collection. If you don't mention the collection, the name of the file itself will be considered as the collection. Now, since the name of the finalists context data on already have a collection called Contacts, it is good to get the name of the collection. So it's a doctor's collection, and then I say contacts. I know the last option, which is the name of the file. The part that I'm giving here is related part because I'm already in the sequel and users we don't fold. It related that there is a folder called esta Andi. There is a context underscored it our Jason. So if everything is OK, you should inboard 1000 documents. And now we can go and have a look at that. You know her mongo shell eso I can just give a command db dot Contact starts, for example. I can say count and then they will give me 1004 because four documents we added earlier and now closing documents have been inserted, uh, through the import command. I forgive here db dot contact Start find You will see that I see only 20 documents on. Then it says here, type it for more Now it is a short term for literate, so I can not. I eat and I should see 20 more. Ultimately, you can assign the fine functions Return value to a variable, for example against our data equals toe david or contact. Start fine now. Data here is an iterated A If you simply press data, it is as if you wanted to see the 1st 20 documents you can also look through that are. You can also say you are Contacts equals toe data. Dart toe may toe convert that into another object. Now I can say contacts off zero and that's the first contract contracts off. 1000 on. That would be the 1001st to document Andi like where they can go on access all data. 6. Executing scripts: apart from running a command from with initial that are different ways Mongo db commands can be excluded. So, for example, let me just exit from the motions and then I'm back in the sea Drive users we know folder Commander Bond. So I'm gonna say among go on, then followed by a dash dash evil followed by a man db dot Contact Start finding one on then the name of the little bit that it has to connect toe when I want to issue this command. So which is test to TV in this case and you can see that it connects to the local host Onda to 7017 That is the before port connect shoot STB and then issues that command. Obviously, this would be a very difficult mechanism If you want to issue more than one commander If I take mongo and Dash Trish, even Onda use Esther db semi colon and I say db dot contact Start finding one. You'll see that it's going to result in tow an error. So what? We can do it. Ultimately, we can create a script file on, then execute the script file using the Mongol Command this would be a good option, especially when you're learning. So in order to test videos commands, let's clear work folder for ourselves. So it's going toe r C drive, create a new folder called Mongo Devi Dash examples and then use the same thing in sublime text. So now we have, ah, folder Andi fights. That's also get into that directory. So that's gross et City. Among would be be dash examples. Onda. We can issue the commands from here now, so it's scary new. Fine. Let's call this as the x 01 dot Js. So let's have a big issue. More than one command here, for example. I want to connect to a database called Test two db on, then semi Colon. And then I can say David or Contact start, find one on. But then I can see here OIR count equals toe Devi Dart contracts start Count on, then I can even say print. There are plus count contacts. So now I have a script that actually can do some work and then I want to execute the same thing here so I can come back to the command front and then is a mongo and then a less than symbol, like an input redirection. And then I'll say egg 01 door. Cheers. Now this should connect to the local whose 27017 use the tested baby and then he should the rest of the conventional death on, as you can see, that the commands have been successfully executed. So in order to test various commands, let us follow this approach. 7. save() v:s insert(): Let's take an example where I have a variable P one he calls to an empty object this time will also assign an underscore i d equals to one. We wondered. Name equals Toe Smith. People in Dark City equals to the last. If I said db dot contact, start insert P one Onda run the scene. You'll see that it gets executed successfully, and it has given his own seeing that the end insulted is one. However, if I run the same thing once more, we get another. Because the underscore idea is more or less like a primary key off Ali VMS tables. So we cannot have the same idea now. Sometimes this may be a problem because we might have retrieved the data from the database and then we would have modified, and we would like to save it back to interrupt the insert. If I use a sale function, Onda run the same. You will see that there is no error. How about this time? It says number off. Match to document is one absurd ID is zero will come toe the concept of observing, but at this time it is number off. Modified records is also zero. That's because we didn't make any changes. However, instead of Smith, this is Martin on Dsev Days on the run. The same. You'll see that this time. It says number off modified documents is one, and that's because we we have some different values. They did not answer, but it's just updating the existing document itself. 8. Projection: Theo calling the find function on a particular collection Rich use all the documents on all the documents include all the properties. Now, sometimes you may want toe Restrict the number of documents based on certain criteria are restrict the properties that you want to view. This is called selection on projection. The first parameter is an object representing the criteria that you want to use for selection. I will come back on that in few minutes. But first we will see how to do a projection. The second perimeter here is the projection. For example, if you want Oh Regio only the first name last name on city off the people in your contact list Then you can simply say here first name iss One last name is one and then city iss one the Internet one We can also use any non zero number So zero represents funds non zero represents true In fact, you can also type the JavaScript keyword True to say that include this particular property When I saved this on then execute the same thing. If execute mongo on then pass on the exito Tito chairs, you will see only certain properties are being returned and especially first name last name City. Now by default, the underscore idea is always included. If you don't want that, you can come back to your command and then say understory is false are zero. So save it on gun the same command again on you can see that we get only first name, last name and city if it exists. If the document does not contain a specific property, that property will not be included. And if it doesn't in any imagine property just an empty object is being written. One very important point that you have to remember is you cannot have a combination off inclusion and exclusion except for the underscored I d Apart from the 80 if you use inclusions for the properties like one are non zero are true. You may not be ableto specify expands for other fields. For example, If I try this, we get another saying that projection cannot have a big soft inclusion and exclusion. So either exclude all the fields that are mentioned here and the two remaining ones are into only these feels and do not get any other fields from the documents 9. Selection: Now that we have seen a prediction, let's see how to use selection. Now the concept is the same thing. You have to specify an object representing conditions. For example, if I want to get all the contract from City off Chicago so I can do the same thing like db dot contact, start find the first argument would be the selection, and the second argument would be the prediction. Let's say, for example, I don't want to include the i. D. I can simply say I ve zero. However, we want to specify a condition here on that condition would be city in Chicago on Save it on, Let's go and run the same thing Mongol exit afford RGs You can see that we got some records now just to make sure that we see the data property that's also called the pretty function . Save it Onda. We execute the same command and this time you can see we got some documents where the city property equals toe Chicago giving a key value. Pairs like this is equal and off saying city equals to Chicago, so the same thing can also be represented using city on. Then we specify an operator, which is given in the form of another object, said Dollar e. Q. And then we give Chicago. So now we are saying that city equals toe Chicago so outward should remain the same thing on we got the same thing. 10. More queries: work with more complex queries. We need to have more complex state. So I have a file here called Sales Death Date. Other dogs. The extension doesn't matter. But if you look at the file carefully, this is not a Jason Ari. For example, Jason Fields must have double correct text, and also an array must have started their square record on every Jason object must have a comma, but this is just a collection of Jason objects, one object but light. So let's import the same in tow among with the big collection. For that, let's issue the command. Mongo Import on the TV is tested. Levy, on the file that we want to use, happens to be called sales data dot dogs. If you don't mention the collection name, the base name of the file will be used, which is sales dash data. Now I would like to have this as a collection called Sales, so I'll see your data collection says. And when I pressed Enter, you'll see that it has imported 286 document Let's go and have a look into that in the Mongol shell. So we have the sales on the DB dot sales start, find and I believe is a pretty format to prettify the same thing. We can see that all the documents are lined up with an automatically generated underscore. 80. Now it is important to see that we have some new medical field suggests quarter and sales amount etcetera. Now let's work on this. Andi execute some more complex varies. Let's everyone acquiree for our sales collection and get on the sales where the sales amount is more than R equals to $10,000. So the quite it would look something like david dot sales don't find and the quality is on the sales amount. So it's a sales amount, and then we use another object and say, dollar G t E. And then the amount, which is $10,000 itself. And if you want to prettify the or put let's call the pretty function as well Syria, it and then I would say Mongol less than e eg zero fighter Js on. We get a bunch of documents that satisfy that condition 11. $and $or $in Operators: way Want tohave on the sales were the sales amount is between $5000 on $6000. Obviously, we need to give a more complex quiet. So let's go and create a new one. And then let's call it US x 06 start Js. So the quite it would look something like db dot sales don't find on the field that we want to test. Is sales underscore amount? It is good to then r equals toe fighters and and then we also want to specify that it is less than or equal to 6000. So obviously we have to give multiple conditions at this time. So the quiet go something like this to David art sales start, find and we'll set dollar on and which is an array off one or more conditions and the conditions are themselves objects. Where will they sales underscore? Amount greater than r equals to 5000. This is one condition and then a similar condition. Where we say sell someone is less than r equals toe 6000. So there's gonna be lt So we save it on, then run the same. Of course, we also like to do a pretty to make sure that we get the different output, but it's execute the team. Mongo e X 06 torches. So you continue to get a bunch of documents where the sales amount is between five and $6000. Suppose we want to find out all the fields done in the quarter one our Quarter three. So there are two ways to do this. One is using a Our operator are the other one is an in operator. Let's begin with our operator. So with a DVD art sales don't find with a dollar are on Dari off criteria, and each creditor is given as a Jason objects themselves, since this time it's just 1/4 equals to one. Our father equals 23 We can just say quarter one and then another object we say quarter is three. They should fit the desired results, So we'll also do a pretty. As you can see, there are a bunch off quarter three documents and then if I scroll up, you see quarter one document and you don't see anything else. So this is one way to go on. The second admitted to do the same thing is David Art sales Start, find And then we simply say, quarter on the operator is Dollar in, which takes an R A. Off values that match the quarter, which is one and three in our case. Then, as usual, will also where three different save it. Andi, run the court. We get the similar results. You can also combine multiple criteria one after the other to give the effect often and operation. For example. Db dot still start find that's a category is equals toe beverages. And then I can give a comma and give another condition that can say, for example, quarter dollar in and then again say, 103. They checked what in the total number of seals. By using mango eg 08 30 years, you'll see that there are 22 documents that match this criteria. But if I include our if I remove this condition on, then try the same thing once more, you will see that there are more number of products that are 46 documents that match this condition, so giving multiple conditions are going to narrow down. There isn't so I can also add another condition. Sales amount greater than R equals two, and then you say, for example, 5000 would further reduce the number of rows, so this has the same effect as combining all of them using the and operators. 12. $where operator: There is also a simple mechanism toe work with conditions. This can be done with the help of a dollar. Were operator which takes a string representing a condition. However, these conditions would operate on the properties using the JavaScript notation. Let's take an example. Did our sales start find dollar were onda strength and here the properties must be access to with the help off this Cavor, where this represents the current object, our current to document being processed. So what mongo DB does is mongo db going to take every document in the sales collection one by one and checks this condition? Is it true for the current to document? And if that is true, for the current document that is prepared for the airport, if not its signal? So if I do hear this start quarter equals two equals to one north, is that double quotes? Because it is javascript. And then I can say our I can say this start quart of equals two equals to treat. This has the exact same condition as in the dollar operator, where we said quarter equals toe one, our quarter records to tree. So let's give it a try and see how Maney documents match this condition. So I'm gonna go type here. Mongo e x 09 dot Js andi It's coming back with 138. So if I go and change this to say, for example, for now, I should see a different result. We can also say something like they start sales underscore amount greater than R equals to fight. Chosen on they start sales underscore amount less than r equals to 6000. So this is a very simple mechanism. Toe executor quietly. 13. Aggregation: using grouping techniques, we can get some rest data from a collection. This can be done in a couple of different ways. Let's have a look at the aggregate function First for this demo, I'll be using a collection called Employees. Here is what it looks like. Let's say we want to find the total number of employees in a particular department. So this is what we can do. BB dot employees start aggregate the first perimeter to this is the grouping option. We have an operator called Group, and then we have to specify what is the I d to be used. The idea here is a property on which we want to group, since we want to find out the total number of employees working in a department. So this has to be a department and in order to specify that this is not a value, but this is one of the property. We prefix this with dollar, so hence we have to use dollar department. This is followed by the new column, our property that we want to get so which may be an employee count, and we have to specify how this country is calculated now Unfortunately, there is no operator called Count, so what we can do is we can repeatedly ad one using the some operator for every employee in a particular department and excuse us the count of the employees in this particular department. So let's save this on, see if you can execute the same as you can see. We have a nice somebody off department and the number of employees working in that department. Let's take another example this time. I want to find the average salary off every employee in a particular department to do so. I can just commit this and let's ride one more quality. Db dot employees dot aggregate. As in the previous case, the I D property would be the department and dollar department. I've read salary for that particular department, and we can use the operator called Dollar. Every G on the field salary once again like dollar department, were using dollar salary because if you do not give dollar salary, but just salary will assume salary is a text and not a property, save it and run the same command and we get the average salary in each department. We can also use the match operator to reduce this output from displaying all the average salaries to only where average salary is more than a particular limit are less than a particular limit, for example, that we want to display those departments where an employee owns an average of more than $4000. So I can use another operation here and I'll say, Dollar match on what is a match criteria. You know, case, we wanted to say the average salary to be greater than our records, too. 4000 save it on the same commands, and this time we'll see a smaller subset where every average salary printed is more than $4000. And if you want to order the output in a particular ascending or descending order, we can use that as the third a perimeter to the aggregate function. So we lose a dollar start, and then we specify the property on which we want to start in this case, a V g salary, and if you want ascending, you can give it us one. If you want descending, you can give it us minus one. That's a bit and execute the same. And here is the output 14. The mapReduce function: Another great tool for grouping Mongo DB documents is a function called Matt Produce at first to this malu clearly complicated, but this has got more power than the regular aggregate function, so let's go check this out. The map reduce function takes couple of parameters first, that's a db dot employees dart map reduce. The first argument is a function typically named this map. The second perimeter is a function generally known as reduced. The 3rd 1 is a bunch of options that begin someplace now, at this time, all these are considered as variables, and I don't have these variables. Let's create one by one function, map, function, reduce and who are options, which is an empty object at this time. The map function will be executed for every document in the employees collection, and we have access to that in the form off this, the map function generally called another function called Emmett with sense a key to be used, for example, distort department and then a value that we want to summaries, for example, distort salary outcome off The map function is a key value based collection where we will have a unique department names as Keith. And for every department we will have an array off salaries. Now that collection is supplied to the reduced function with a key on values. If this malfunction was called for every document and we have, let's say, for example, in number off unique department, the reduced function will be called exactly N number of times were a key, which is the department on then Aria off. All the salaries is supplied. So what we can do here is toe return, an object which is a summary off. This particular values, for example, I can simply return are a dot some off values, which means we're summing up all the salaries for a given department and returning that so that would come off this raid dysfunction is that mongo DB takes the key Onda summarized salary and then we'll add it to its bucket at the end of this, the inter bucket, which is a key on that some of salaries will be given to us. This options tells us whole 200. The response data on at this time we can simply say out is inland, save it and then we can just access this as Mongol. He extradition Doctor. Yes, and we have a summary report. So if you carefully observed, each department is despaired. One thing and this happens to be that some off all the salaries. In the beginning, I mentioned that my producer offers more power than the typical aggregate function. That's because we can control whether or not a particular piece of data is emitted based on certain conditions. For example, if I don't want to include the salaries less than or equal to 4000 I can do so by simply adding a condition. If this starts salary is less than or equal to 4000 return, which means out off a number of documents in the employees collection, certain off them are ignored based on this condition. So now, if I say and access the result once more, you'll see that the numbers are different. Andi smaller compared to the previous one. Also, we can are less number of departments to include, for example, that I don't want to include sales, services, support and training. I cannot one more condition, save it, execute the command once more, and you will see that in the awkward. We do not include sales supports our visas on training departments 15. Indexes: by the for mongo. DB scans every document in a collection to select those which matched the query condition. If you have a query that uses a particular field on the queries used by the client's quite often, then we can create an index for the field so that the performance of the query can be increased. Mongo DB offers different kinds of indexes On the most common one is the single feel index . Before we create this index, let's have a look at this command. We are searching a contact using a phone number. We can ask mongo db as How did it arrive at this particular result by calling the explain function on the find. The result shows which one is a winning plan on the winning plants is that it is called scan. Basically, it is. The phone number was searched by matching this phone number for every document until it phoned Are it is not found. This is quite inefficient. If the quality is repeatedly being used, you are like this. We can now use index first. Let's see what other indexes that are currently available by giving db dot contact, start, get in excess and It says that there is only one single index on the field. Underscore. 80 underscored. The property is indexed, ready for for all collections. For example, debido our employees dart get indexes also shows me that there is one index on the Underscore 80 and we can go and check for all the collections. And the story is saying now, let's create a new index for the phone Property of contacts To do so db dot context dot create index and then we have to say phone to be indexed. Now it gives me a message saying that number of indexes before was one. A number of indexes after is, too. We can verify the same thing by issuing the client again to get the indexes, and we do see that there are two off them now. We can also ask mongo db toe, explain the quality If we executed no. And now you can see that out off many plans it came across with. It Now uses an I X scan, which is nothing but index can. If you want to drop the index, db dot contacts dot drop index and then specify which is the property on which you want to drop the index, so I have here for as the property and then I can just say drop indexes. It says number of indexes waas too, which means now it should be only one. We can also check it out by getting the index is listed, which is that there is only one, and also we can check the explain functions result, which is now going back to the call scan. 16. Updating documents: Let's have a look at updating documents on for updating the documents. Let's take a different collection. Andi. I have another Jason are a document called Products. Start Jason. Let's import the same thing into our Mongo DB database. To do so. Let's execute the Mongo import for it. Jason Buddy Onda database that we want to use the testily be on the collection that we want to use is the same name as the product, so I can just type your product. Start chase on now. Since we didn't mention the collection name, it's going to take the base name off this file, which happens to be product. So that's execute Andi, it says imported 85 documents. Now. One thing you can observe this time is that if I run the command once more, it's going to result in tow. Others on. That's because if you observe, we already have underscored idee property for every document. If you try to insert again with the same underscored Heidi, we get the other. So now that we have got all the documents inserted, let's have a look at what exactly we have. That's it. US. Test two db show collections And this time I want to say, db dot products Start, find don't pretty Let's say we want to modify a data for one off this product. For example, let's say the name off this particular product for 19 instead of branch all I want to change this toe eggplant, And to do that, we would be using the update command. So we'll say db dot broader start update. So the update takes a few parameters. The first Fatemi turn off this update function is the quietly so the quiet he happens to be underscore. Idea is 19. The second is the document that you want to do. Now if I just say that I want to change the name off this from brindle, toe eggplant and press ender. Now it says that number off documents match this one number of absurd documents. Zero a number off modified documents is one. And if I go and have a look at whether it has updated or not, David, our products start find dot pretty Andi, you should see that the product number 19 is changed, but not as we expected. We wanted the name to be changed, but it has replaced the entire document. So this was a bad idea. So in order to change only one or two properties often entire document we should be using an operator called Set. For example, let's do the same thing for this one. Except that incident the brand fresh. Oh, I want to change this to Grand Mal Not and to do so this time I'm going to use db dot products Don't update. I'll say the same quality this time underscored ideas 20 Onda Then the document that we want to update happens to be dollar set. And then we say, What are the property that we want to set? So I'll take your brand happens to be my lord And if I want, I can also add another property which is currently not existing, for example, I may say that details Andi, I can say you're something like this, which I don't have any details at this time. So I closed the bracket for the set operators on the clothes, the bracket for the modifying document and that's the end of the update function so I can execute the same thing again, the same result, it says number of documents matches one number off absurd, documented zero and modified document is one unlike the previous one. Now, if I execute the find method to redo all the values, you'll see that the document 20 is intact except the brand has changed. A new property call details is added. 17. The upsert operation: suppose I wouldn't find apart. It was ID's 100 then I want toe update few properties off the product. So we would say, db dot products dot update And the quality is underscore. Idea is 100 and then the updating document happens to be a new one. Probably I can say name equals toe test product. On that, I would say Unit price happens to be, let's say, 100.0 onda a description off the same thing happens to be best description for No. I think these property should be good enough. Let's save this and then run the same thing to run there as a mongo. Less than e extend R. J s press enter and it comes back with a result. The results says number off matched documents zero Absurd zero modified zero. The reason is very simple. We don't have the document with a 90 off 100 so let's go check it out. I go to the mongo test to levy and see DVD dot products. Don't find underscore Idea is 100 on. You can see that it came back with nothing. We can also ask Mongol Bebeto, insert a new document in case if the update failed that this concept is called upsetting. So we come back to this particular chord and then we specify here a terror perimeter where with a absurd is too. We said that search for this document. If it is phoned, you need toe change this as the new document. If it's not found, you need toe ire, that updated audience it So one more thing is that if the product already existed with multiple fields, all the fields will be lost and only these fields will be the new fields. So in order over that, I can say dollar set and then we can specify all these properties. So let's execute the script and check the result. And this time it is number off match documents. Zero. Number of absurd document is one modified A zero The i D. Generated happens to be 100 and that's because we supplied that. Let's go on very for the same thing, like mongo, test to Davies. And then it's a db dot thought it start. Find one with an i d off 100 on they receive. There isn't 18. Updating multiple documents: Let's everyone increment the price off all the products off fresh whole bran. So first, let's find out what of those products. So we get into the Mongo Shell. That's to date of this. And then I'll say, db dot products don't find and I'll give the conditioners brand is fresher Onda. We can also see a pretty so that we can see the results properly. So there are many of them. Let's see the last few off them where the product price happens to be 29 35 39 and we want toe check if that increases the product's price for all of this. So let's right the quiet for the same things with a D v dot products start update and the criteria happens to be brand equals two official and then toe increment. The price we can say dollar I. N. C. For inclement with a unit price on the amount being incriminated lets everyone to incriminate is by ₹5. So it says here that find all the products with this brand facial and then increments the unit price by five. So if it is 30 it should become terrified. Terrified becomes 40 and so on. So let's see if this works saved this. Andi, execute this when execute it says number off documents matched one Absolutely zero modified his one. But we saw there are many, many documents matching that condition, but there was only one update took place. Now this is because by default, mongo db opted the very first document that it finds Not since in this case it was quite arbitrary. We don't get the desired result. You can go and verify that. Also, ultimately we go here and then specify 1/3 option where we earlier give absurd. This time we don't want to Really absurd. But we can say your multi as true now by default Multi has been set us false. So we save this. Were under same thing again on defense it This time it is Master documents are 56 modified documents are 56. So we can also go to the Mongo shell. Onda, check Devi Dark Products start find Onda with their brand fresher Well, so say pretty. So if you remember the last few outputs we had Ah, 35 For this We now have 40. We had 39 it is 44 we had 29. That's changed 234 So this way we can update multiple documents as well. 19. Removing documents: way. We may also have to delete a couple of documents. This can be done by calling the remove engine on a particular collection. For example, if I want to delete a document whose idea is 85 so db dot products start fine. I d. Is 85 so you can see that it has this data I can give a command db dot product start removed on the creditor. Being idea is 85. This actually most the document once for all so you won't be able to do an undue operation . So you should be careful when you're doing this. Deal it. We will say the same command again to retrieve the data. We don't have the data, so we don't see Suppose if we give devi dot products dot removed. We're brand happens to be fresh old. You can see that it d leads 55 documents, so that means all the documents that master condition got deleted. Sometimes if you want only one document to be deleted, which is very unlikely, you can also include just 21 as true against a DVD art broader start every move and then the similar condition brand happens to be muller, and then I can see just one. It's true, this actually removes on your one. But as you can guess, we don't know which one has been deleted. 20. Thank you: Congratulations on completing this course. This goes end here, but learning continues. I hope you benefited from this course. Andi. Enjoy learning. As much as I enjoyed creating this course, I sincerely thank you for purchasing this course and wish you success in your future. If you have any doubts, are questions in any off my lectures and demonstrations. Don't hesitate to get back. Your feedback helps me employs ing my future courses once again. Thank you and wish you all the best.