You are on page 1of 51
A -_ MONGO DB ‘Syllabus Understanding NoSQL and MongoDB - Building MongoDB Environment - User accounts - Access control - Administering databases - Managing collections - Connecting, 0 MongoDB from Node js - ‘imple applications Contents 3,1 Understanding NoSQL and MongoDB ” 3.2 Building MongoDB Environment 3.3 User Accounts 3.4 Access Control 45 Data Types in MongoDB 3.6 Administering Databases 3,7 Managing Collections 3.8 Connecting to MongoDB from Node js 3.9 Understanding the Objects Used in MongoDB Node js Driver 3.10. Simple Applications : etc 3.11 Advanced MongoDB i 3.12 Two Marks Questions with Answers aa Full Stack Web Development Understanding NoSQL and MongoDB NoSQL © NoSQL stands for not only SQL. A * Itis nontabular database system that store data differently than relational tables, Th are various types of NoSQL databases such as document, key-value, wide Column ang graph, * Using NoSQL we can maintain flexible schemas and these schemas can be scaled easily with large amount of data, Need : The NoSQL database technology is usually adopted for following reasons - 1) The NoSQL databases are often used for handling big data as a part of fundamentay architecture. 2) The NoSQL databases are used for Storing and modelling structured, semi-structureg and unstructured data. 3) For the efficient execution of database with high availability, NoSQL is used. 4) The NoSQL database is non-relational, so it scales out better than relational databases and these can be designed with web applications. 5) For easy scalability, the NoSQL is used. Features : i 1) The NoSQL does not follow any relational model, 2) It is either schema free or have telaxed schema. That means it does not require specific definition of schema, " 3) Multiple NoSQL databases can be executed in distributed fashion. 5 4) Itcan y ull Stack Web Development 3-3 MONGO DB why MongoDB is needed ? ‘There are so many efficient RDBMS products available in the market, then why do we need MongoDB ? Well, all the modem applications require Big data, faster development and flexible deployment. This need is satisfied by the document based database like MongoDB. Features of MongoDB 1) It is a schema-less, document based database system. 2) It provides high performance data persistence. 3) It supports multiple storage engines. 4) Ithas a rich query language support. 5) MongoDB provides high availability and redundancy with the help of replication. ‘That means it creates multiple copies of the data and sends these copies to a different server so that if one server fails, then the data is retrieved from another server. 6) MongoDB provides horizontal scalability with the help of sharding. Sharding means to distribute data on multiple servers. 7) In MongoDB, every field in the document is indexed as primary or secondary. Due to which data can be searched very efficiently from the database. SQL Structure Vs. MongoDB Following Fig. 3.1.1 shows the terms in SQL are treated differently in MongoDB. In MongoDB the data is not stored in tables, instead of that, there is a concept called collection which is analogous to the tables. In the same manner the rows in RDBMS are called documents in MongoDB, likewise the columns of the record in RDBMS are called fields. 3-4 MONG 04 Full Stack Web Development database in the form of table and to the right hand gj «To the left hand side we show the f collection. 5 i lecti the database is shown in the form of co! Collection id'-527f191e810c19349de8600g, "Name’."Ankita’, *Course':;Computer Engineering", ‘Address":{ Doe nine1'"Lanel” ‘ment ‘ine2'"Lane2" t bh * {a"'5571191e810c19729de8602a, Name] Course | AddressLine1|AddressLine2| | ayame"Prajkta’, tg) Computer Tene Lane2 *Course':’Mechanical Engineering", Ankita | Engineering "Address':{ Document Mechanical “line1":'Street1", Praia! engineering || _Sieet! Street2 “line2"'Street2" F Civil t Kavita! Engineering | _ Roadt Road2 } Fields ——}—> ‘Course":'Civil Engineering’, "Address" Doct ‘line1":"Road1", ety “line2":"Road2" } Fig. 3.1.2 Review Questions 1. What is NoSOL ? What is the need. {for it ? Enlist various, yaa of NoSOL. 2.__List and explain various Sais of MongoDB, : Ba pischiwed Develonment 3-5 MONGO DB de Open File - Security Warning Do you want to run this file? Name: .oads\mongodb- windows-x86_64-6.05-signed.msi Publisher MONGODB, INC, Type: Windows Installer Package From: C\Users\DELL\Downloads\mangodb-windows-x8. is Always ask before opening this file 2 While files from the Intemet can be useful, tis file type can potentially harm your computer. Only run software from publishers you trust. Whats the risk? Welcome to the MongoDB 6.0.5 2008R2Plus SSL (64 bit) Setup Wizard ‘The Setup Wizard val instal MongoO8 6.0.5 2008R2Fus SSL. (G4 bt) on your computer. Click Next to continue or Cancel to ‘eatthe Setup Wizard. installation. Follow the ‘do not want to install the icheck the option. TECHNICAL PUBLICATION 3-6 —— Moy Full Stack Web Development NGO Completed the MongoDB 6.0.5 2008R2Plus SSL (64 bit) Setup Wizard (ic the Fish buton to eat the Setup Wizard Click on Finish button, to complete the installation process. In order to verify whether it is installed correctly or not, go to command prompt window and execute the command for mogod.exe file’s version. It is illustrated as follows - CWindows\systems2.emde x | Microsoft Windows [Version 10.0.22621.1555] } (6) Ricrosoft Corporation, AN Saaeey Hee, ¢:\Program Files\MongoDB\Server\6, @\bin>mongod “exe ~-version db version v6.0.5 | Build Info: { "allocator": "envirennent' Y C:\Program Files\MongoDB\Server\6. To set the environment variable, Open System Properties and click on Enyironment Variables Pee paiciecxiWvebiDetelopment 3-7 MONGO DB ‘Yourusi be logged on as an Adminstatotto make mos ofhese changes | Petormance Visual efects processo: scheduling memory usage, and viual memory User Profies Desliop setings relatedio your signin ‘Statup and Recovery ‘System statip system fale, and debugging wlomaton ChocolsteyLaPatlpdate 132SSOISITSTIEN | | a erect eee || oneorve \WsewiOELOnedrve || onereConumer Cir DEL ede f || pat ClWsen\DELAppDat\ocaMitesoftWindowsboosCs. | ] raw CC\Usem\DEL\AppOata\ Local emp | > ane \Uses\ DEL AppData Local Tem | Spe arabes Vote be hocolateyrtall CiprogamData\checlatey I input, \Pegam Fle 150 briny comecor jae 5— omsec Ch Windows ystens2endere ; Dive Windows Sytemi2 Divers DveData | INIA HOME aPogram esa 1501 | OF PROCESSORS. 8 windows NT a Full Stack Web Development $28 MON + 0 Then click on the path variable and set the path of MongoDB by Clicking New oy button ~ Eat envronment variable | CAUses\DELL\AppData\Locl Programs\Python\ython3 1 Scr. | C\Users\DELL\AppDataLcaPrograms\Pyhon\Python3 10) USERPROFLER AopDatal Local Mest Windows | CkesiDEu opOsa\ Local PogamWico VS Codetbn \Wses\DAL\AppDaa\Roaning\em | C\Pogram Fes MongoD8\Sene\6an Then simply continue clicking ok button and just come out of the environment variable window. Installing Mongo Shell For working in MongoDB shell, the shell Is separately installed. For installing it, go to the website https://www.mongodb.com/try/download/shell Click on Download button, The Zip file gets installed, Just unzip this file to get the MongoDB shell installed. Then set the environment variable to set the path for MongoDB shell. In my Present at the path C:\MongoDBSh\mongosh-1.8,0-win32-x64 hence I will add the New path in the Environment variable tab 1.8.0-win32-x64\mongosh-1 .8.0-win32-x64\bin” case, the mongosh.exe is \mongosh-1.8.0-win32-x64\bin, as “C:\MongoDBSh\mongosh- TECHNICAL PUBLICATIONS® - an up-thrst for owledge —naiililliaaima Yr 00, y stack : Web Development 3-9 MONGO DB. ~ ae Edit environment variable (C\Users\DELL VAappData\ Local\Programs\Pytnon\Python3T0\Scn_ | C\Users\DELL\AppData\Locai\Programs\Python\Python3 1, ‘USERPROFILERAppData\Local\Microsoft\WindowsApps | C\Users\DELL\AppData\Local\Programs\Microsoft VS Code\bin | C\Users\DELL AppData\Roaming\npm C:\Program Files\ MongoDB\serven\6.0\bin Edit text. Cancel To verify the installation, open the command prompt and issue the command mongosh. The test> prompt will appear as follows - Current Hongosh Log ID: 6114124333492e9c¢0b6931F7 Connecting to: i 278: cc Using Mongod8: 6.0 : 2 : 5 ! 8 ° | For mongosh info see: https: //docs.mongodb. com/mongodb-shell/ | _2023-04-20716:39:36.203405:30: Access control is not enabled for the database. Read and write ac | cess to data and configuration is unrestricted Enable MongoDB's free cloud-based monitoring service, which will then receive and display metrics about your deployment (disk utilization, CPU, operation statistics, ete). The monitoring data will be available on a MongoDB website mith a unique URL accessible to you and anyone you share the URL with. MongoOB may use this information to make product Amprovenents and to suggest HongoDB products and deployment options to you. To enable free monitoring, run the following command: db. enableFreetonitoring() To permanently disable this reminder, run the following command: db.disableFreeNonitoring() TECHNICAL PUBLICATIONS® - an up-thrust for knowledge Full Stack Web Development 3-10 Me ONG, Hetty Installing Mongodb Compass (Graphical Too!) This tool is very useful for handling MongoDB database with the help of Simple gr user interface. Offers th Sarde docusent motel along wih id Roe Qoalel de See Select any suitable version 48 per your operating system. As mine is a Windows operating system of 64 bit, I have chosen following option. Available Downloads a Vernon 5 : 1.260 (Stabie) Ys Paton ——a'! Windows 64-bit (7+) (MSI) v Development py took Web Click on the Download button, The exe file will get downloaded. Double ¢ fil which is downloaded in your PC and the installation process for MongoDE ile start. 9 Mongo08 Compass Setup Welcome to the MongoDB Compass Setup Wizard The Setup Wizard wil instal WongaD® Comp3ss Of YOU compiter. Click Nex to continue or Cencel to ex the Setup Wicerd. simply go on clicking Next button and then. click on the install | window. Finally you will get the installation completion sereen- [i Mongob8 Compass Setup Wizard 3-12 i Full Stack Web Development ot —HONen i O i dows, | a ick Fini k the Start button of Windows, locate Just click Finish button. Now, lig a é Pay Compass Application and simply click it to start M ac Will & following GUI T New Connection @issne Fle connect linda Paste your cermin sng (SRV Now Compass and donthave a chatry Standard) Ay dot ated tw alas you a, ‘roam ora to ug Min (GREATE FREE CLUSTER ) How do fr my coanetion sng in i? Aya have a Ate cht 90 the Out Ya Cit Geen tata rt to wich ou ws tcomect Scour ow o format my comecton sing? Ife click the connect button then we get following screen coneera ce ee a Siaok Web Developren 68) MONGO DB User Accounts MongoDB stores the information of all the users including name, password and user authentication in the system Using MongoDB shell command we can create the user accounts. Using such user accounts we can read and write to the databases, The most commonly used operations are 1. List the users 2. Create the user accounts 3, Remove the users Let us discuss them one by one. fe sting Users User accounts are stored in db.system.users collection of each database. There exists an object named User which contains the fields like _id, user, pwd and roles For listing the users in the system, switch to admin database and then use show users command. {_ mongosh mongodb://127.0.0. x | test> use admin | switched to db admin dmin> show users admin> ‘As no user is created, it is showing empty. Another query is using find(). The db.system.users.find() retums a cursor object. Then using count() method we can obtain the total number of users present in the system. For example - TECHNICAL PUBLICATIONS® - an up-thrust fr knowledge Full Stack Web Development___ test> use admin i to db admin 3 i eee = db.system.users.find() EE Create User Accounts The user accounts are created using the createUser() method. Syntax db.createUser(user, ‘writeConcern) Parameters user : is a document with authentication and access information about the user to create writeConcern : Vhis document represents the level of write concern for creation Operation The user document has following fields Name Description Type user The name of the new user. string pwd The user’s password. The pwd field is not required if we string run db.createUser() on the $external database to create users who have credentials stored externally to MongoDB customData Any arbitrary information. This field can be used to store. document any data an admin wishes to associate with this particular user. For example, this could be the user’s full name or employee id. roles The roles granted to the user. Can specify an empty array array [ ] to create users without roles - ee | mn, ck Web Development 3-15 MONGO DB pull S18 The role can be specified as Now gore! “"s For example - db: “"} mongosh mongod! | admin> use test switched to db test coee db. createUser( 3 Ba rene "Parth", I * ve. pwd: "Parth123", } ... roles: [] eet { ok: 1} test> to test, if the user named Parth is created or not, we issue the show users command at the MongoDB shell mongosh mongodb://127.0.0. _test> show users nid: ‘test.Parth’, UserTd: new UUID('59bb3031-F90F-Wd1e-9749-801469e4e645") , | user: 'Parth', db: ‘test’, roles: [1], ae [ 'SCRAN-SHA-1', 'SCRAM-SHA-256' ] a test> The above user is created without any role. But we can assign the role to the user during the createUser command. PUBLICATIONS® - an up-thrust for knowledge wp 6 MONGg él (Eid Sock eb Deon eee ~O0y Creating the user with roles assigned to the Following is the list of some commonly used roles that can be assign USer agg, On Description Role a iny collection withi read ‘Allows the user to read data from any ‘thin database. readAnyDatabase [tis similar to read except on the local and config databases readWrite This role provides all the privileges of the read role plus the ability to modify data on all non-system collections. dbAdmin This role allows the user to read from and write to the database, as well as clean, modify, compact, get statistics profile and perform validations. dbAdminAnyDatabase Same as dbAdmin except for all databases. aa This role allows the user to create and modify user accounts on the database. | i ae userAdminAnyDatabase Same as userAdmin except on the local and config databases, For example - : { . = tS ‘user: "sysAdmin’, wd: ‘pass123", roles:['readWrite’,"dbAdmin’) : } : kb Following screenshot represents how to create user with role. ped: *passi23", + roles: ["reacirite* ee) - pull stack Web Development Sail MONGO DB Remove Users For removing the user, the db.dropUser() is used. syntax gp dropUser(username) For example {g&_ mongosh mongodb://127.0.0. | test> db.dropUser("sysAdmin"); _{ ok: test? By above command the user named “sysadmin” is remov ed. Review Questions 7 Explain how to create users in MongoDB ? Also enlist and explain various roles of the users. 2. How will you remove the user in MongoDB ? Explain. EX] Access Control e User exists in context of a single database. MongoDB provides authentication and authorization at database level. © For basic authentication purposes, MongoDB stores user credentials inside a collection called system.users in each database. The admin database does not have any users assigned to it. © The User administrator account provides the ability to create user accounts in the admin and other databases. Creating a User Administrator Account © For configuring the access control, the first step is to implement User Administrator account. aSes Full Stack Web Development ‘ a ONgg reate users and create an assigns roles. A. Tice — © User Administrators ¢ can grant any privilege in the database and can create new ones. i ployment, create the User Administrator as the fj © In a MongoDB de} not manage the database. © Syntax for creating the user administrator account is as Followsk 3 use admin db.createUser( { user:"", Pwd:"", Roles: [“userAdminAnyDatabase]}) For example Creating admin user in the admin datababase | test> use admin | switched to db admin admin> db.createUser( “sysadnin®, :*system123", roles: ["userAdminAnyDatabase"]}) cal admin> show users iG { id: ‘admin. sysadmin’, userId: new UUID("b6a6bedd-U2ca-We80-97de-UBBdea7dU611"), user: ‘sysadmin’, db: ‘adain', roles: [ { role: ‘useradninAnyDatabase', db: ‘admin’ } 1, mechanisms: [ 'SCRAN-SHA-1', “SCRAN-SHA~256' ] 3 Displaying the users from the admin 1 admin> Note that the administrator user is now sysadmin with password system123. We can authenticate the admin database using db.auth command with user name and password options. For example - mongosh mongedbi// use admin switched to db admin | admin> db. auth("sysadmin", “system123"); fobs 2} sb Development ea ET) MONGO DB ‘mongosh mongodbi/ use admin already on db adnin _ admin> db.auth("sysadmin", "passi23"), | HongoServerError: Authentication failed, } adnin> pul BE Creating Database Administrator Account For creating a Database Administrator account the createUser method is used. The assign the roles such as readWriteAnyDatabase, dbAdminAnyDatabase, clusterAdmin. For example - test> use admin | switched to db admin adnin> db. createUser( ee }... user: *ébAdnin*™, + pad: "passuordi23*, roles: [*readMritefinyDatabase", "dbAduinAnyDatabase", "clusterAdain"] a Oy f ok: 1} We can use this user in MongoDB shell to administer the database. Review Question 1. Explain with suitable example how to create database administrator account in MongoDB ? Data Types in MongoDB Following are various types of data types supported by MongoDB. 1) Integer : This data type is used for storing the numerical value. 2) Boolean : This data type is used for implementing the Boolean values i.e. true or false. Bs TECHNICAL PUBLICATIONS® - an up-thrust for knowledge 3-20 Full Stack Web Development 3) Double : Double is used for storing floating point data 4) String : This is the most commonly used data type used for Storing the Sth FE é ‘ d to compare a yal ag: 8 y, 5) Min/Max keys : This data type 1s use Ip Ue againg, the ia Al highest BSON element. i ; Weg 6) Arrays : For storing an array of list of multiple values in one key, this da used. 7) Object : The object is implemented for embedded documents, 8) Symbol : This data type is similar to string data type. This data t specific symbol type. 9) Null : For storing the null values this data type is used, 10) Date : This data type is used to store current date or time. We own date or time object. Moy, 8 & 'YPe is Used tg SM CaN also o, Create oy 11) Binary data : In order to store binary data we need to use this data type, 12) Regular expression : This data type is used to store regular expression, Beery 1. Give various data types used in MongoDB. Eg Administering Databases In this section we will discuss how to create and handle database in MongoDB yg various commands. % (1) Create Database Open the command Prompt and type the command mongosh for Starting the mongopg shell. The test> Prompt will appear. For Creating a database we need to use the “use” command, Syntax use Database name For example -- use mystudents | switched to db mystudents | mystudents> Pa. 6 See ee pu stock . Web Development 9-24 MONGO PB ee gtd To check the currently selected database, use the command db mystudents> db nystudents, | nystudents> (2) Displaying all the databases present in the system d show dbs we can see the list of databases present in the MongoDB using the comman nystudents> show dos ‘admin 180.00 KiB config 72-98 KiB Tocat. 72.00 KiB mystudents> For example - This is because we have the mystudents database. database in the listing by means of Note that in above listing we can not se not inserted any document into it. To get the name of the show command, there should be some record present in the database. (3) Drop Database The dropDatabase() command is used to delete th nystudents> db.dropDatabase() { ok: 2, dropped: ‘mystudents! } | mystudents> | database. For example - 1 i TECHNICAL PUBLICATIONS® - an up-thrust for knowledge 3-22 Full Stack Web Development Moh. Write the MongoDB command to create and drop the database. Managing Collections After creating some sample database we must create some collection inside tha We can perform various operations such as insert, delete and update on : td = this Colle alta, Operations are called CRUD operations, CRUD stands for Create, Reg ction, 8 Ad, Update grt Thy, operations, And pg Cle 1) Create Collection We can create collection explicitly using ereateCollection command. Syntax db. createCollection(name, options) where a pecify some parameters Such ag Size name is the name of collection options is an optional field. This field is used to maximum number of documents and so on. Following is a list of such options. Field Type capped Boolean Description Capped collection is a fixed size collection. It overwrites the oldest entries when it reaches t is set to true, enabled a capped collection. Wh value as true, you need to specify the size pal This field is required to create index id auton value is false. automatically © maximum size, If, hen you specify this rameter, autoIndexID | Boolean matically, Its default size Number This value indicates the maximum size in bytes for a cl apped collection. Max Number It specifies the maximum number of docum collection, jents allowed in capped For example - Following command shows how to create collection in a database using explicit command sst> use myStudents itched to db myStudents eps tents> db -createCotlection( student details”) ol : en a siack WeD Development _ 3-23 ____ mono pB pul —_ a zi tion lay Collect ?) pe at the command check the created collection use the command “show collections” _ pyStudents> show collections Student_details nystudents> 3) Drop Collection The drop collection command is actually used to remove the collection completely from The drop command removes a collection completely from database. the databas syntax ‘ab collection_name.drop() For example mongosh mongodb//127.0.0. x “myStudents> db. Student_details.drop(; myStudents> We can verify the deletion of the collection by using “show collections” in the database. TECHNICAL PUBLICATIONS® - an up-thrust for knowledge mongesh mongodt//127.00- myStudents> show collections myStudents> 4) Insert documents within the collection The document is inserted within the collection. The document is analogous to TOWS j in database. Syntax db.collection_name.insert({key,value} For example mongosh mongodb//127.00. myStudents> show collections myStudents> db. createCollection("Student_details") yee nol: ded myStudents> db.Student_details. insert({"name": "AAA age": 22}) acknowledged: (+ insertedIds: { '@': ObjectId("643e4b63436497399ala2a66") } myStudents> yr. myStudents> db, Student _detaits.find() [ ( Ad: ObjectTd("643e663436097399a1a266"), nam nystudents> yaaa’, age: 2 0] 5) Inserting Multiple Documents It is possible to insert multiple documents at a time using screenshot shows how to insert multiple documents in the existing collection. nyStudents> vor allstudent: a single command. Following at Snane™:"882", Sname™ 000", Sanat re y; | nyStudents> db. Student details. insert (altstudents); acknowledged: ©, insertedIds: { O°: ObjectId(7suses1sdas6u97399a1a2a67"), 1's Object Id("6d3e5184436U97399a1a2268") y } ayStudents> To verify the existence of these documents in the collection you can use find command as follows - mongosh mongedb://127.00 | myStudents> db. Student_details.find() { id: ObjectId("643e4b63436497399a1a2a66"), name: ‘AAA, age: { Lid: ObjectId("643e518dU36497399a1a2a67"), name: ‘BRS’, ag { Lid: ObjectId("643e518d436497399a1a2a68"), nam myStudents> 8) Delete Documents ell 1e document the remove command is used. This is the simplest command. Pane ac eee (oo - Ful Stack Web Development Mong, ty Syntax ab collection name remove(delete criteria) For example - in the collection usi First of all we can find out th = Sing find() com, e documents present Mang {_mongosh nengod/21.00- * | mystudents> db student detail 643eub63436497399A1 (vguge518du36U97399a1a2— (v6us3e518d436497399a1a2268" s.find() a2a66"), name: ‘AAA’ 67"), name: '8B8', ), name: ‘000', Ad: ObjectId(" ObjectId(" 1: ObjectId! myStudents> Now to delete a record with name “DDD” we can issue the command as follows - myStudents> db.. student details.deleteOne({"name": "00D" { acknowledged: 1», deletedCount: © } myStudents> Gamer db.Student_details. find() | { _id: object1d("643e4b63436097399a122266"), name: ‘AAA’, age: ch { Ob jectId("643eS18d436497399a1a2a67"), name: 'B88', age: yStudents> 7) Delete All Documents For deleting all the documents from the Collection, we use .deleteMany(). For example - ‘mongesh mongodt://2 i Sena db. Student_details. delete eM. i ackraslciget Weare ee |) myStudents> We can verify it using db.Student_details.fi are deleted or not. ind() command, we can verify that the records MONGO DB a mengosh mongody/2709,. x } i nyStudents> 8) Update Documents For updating the document wi lent We have to provide Some criteria based on which the document can be updated. syntax {apcollection name.update(crteria update data) For example - Suppose the collection “Student_details” contain follow ing documents 1 rongosh mergoseina70a nyStudents> db.Student details Find() C { Lid: Object1d("643e72de436u97399a1 2369") name: ‘AAA’, age: { “id: objecttec-sssersbaussipriesatanaeasy, fame: (agen! Bel { Lid: ObjectId("643e73b2436497399a1a2a6b") fame: 'CCC', age: { Ad; ObjectId(*6u3e73b2436097399a1a2a6¢"), ane *DDD'| age: ] yStudents> And we want to change the name “CCC” to “WWW”, then the command can be issued as - myStudents> db. Student details update( (Yeane™s CCC"), {00 { name": "awn F) } DeprecationWarning: Collection. update() is deprecated. Use updateOne, updateNany, or bullatrite. acknowledged: bus, insertedId: null, mmatchedCount nedifiedCount: UupsertedCount ‘mergosh mengoat2r00. % nyStudents> db. Student details. find) be { id: object d("643<724e436U97399a1a2a69"), nane: ‘AAA’, { id: Object 1d(%643073b2436497399a1a2a6a"), { Lid: objecttd¢“62e7302436u97399a1a2a6b"), lone Thus the document gets updated. TECHNICAL PUBLIGATIONS® an ups orkrowedge ——— ¥F 3-28 Full Stack Web Development eeeenin., = By default the update command updates a single co © can update a é ‘true iy ea as well. For that purpose We have to add {multi-true} 4 For example : : vader aaa update (Zage" 2) (Sasa -23}},{multi:true}) 9) Sorting We can use the sort() method for arranging the documents in ascending 0, r Sesceng, order based on particular field of document. Syntax For displaying the documents in ascending order we should pass value 1 db.collection_name find() sort({field_name'1}) If we pass -1 then the document will be displayed in the descending order of the field For example Suppose the collection contains following documents. rmangosh mengodt//127 0 myStudents> db. Student_details.find() ObjectId("643e72de436N97399a1a2a69"), Object Id("643e73b2436497399ala2a6a"), Object Id("643e73b2436497299ala2a66"), 2 ObjectId("6U3e73b2436497399ala2a6c"), ayStudents> db. Student _details.find(). sort({"age":-.}) Object Id("643e7362436497399ala2a6e"), name: 'DDD', age: 2 > Object Id("6i3e72deH36497399a147a69"), name: ‘AAA'’ ag Object Id("63e73b2436497399ala2a6b"), name: ‘www’, age: Object Id("6430736236497399a1a2a6a"), name: '8B8', age: ” yyStudent s> Ifwe want to display data in ascending order we issue following command myStudent> db Student details find() sort({*age":1}) mete) ae pap stock We? Development 2228 _MONGO DB” connecting to MongoDB from Node. js For connecting the Node.js with MongoDB we use MongoClient following are the steps used to connect Node.js with MongoDB step 1° Install MongoDB driver for Node,js by issuing following command on the command prompt npm step 2:10 the Node.js application program require the MongoDB module by adding following fine of code Gast MongoClient = require(mongodb) MongoClient; Define MongoDB Connection URL fnstall mongodb step 3: ! Gonst url = *mongodb://127.0.0.1:27017/myStudent step 4 : Create the instance of MongoClient by passing the above URL to it. It is as follows - const client = new MongoClient(url); step 5: Finally use the connect method to get connected with the database client.connect() The complete code is as follows - App.js /jget the mongoDB client ‘const MongoClient = require(mongodb). MengoClients j/specify the URL of the database to which the connection is to be done const url = ‘mongodb://127.0.0.1:27017/myStudent: //Create client instance const client = new MongoClient(utl); // Connect to the database function getData() i client.connect() ‘then(()=>console log("Connected to Database Successfully!!!) \catch(error=> console.log(‘Failed to Connect ,error)) } getData(); Output Works ee ee SSS Parmer te tg ci) eerie gcn inc ot . ce) ean TECHNICAL PUBLICATIONS® - an up-thrust for knowledge 3-30 Mon, Full Stack Web Development 3 ; in above code, ion : pipers am Explanation : ‘mongodb’ using requi ae have to import the module “mong 8 require, Thy: 1) First of all, we creating MongoDB client. 2) Then specify the URL fo number on which MongoD! i ® to create a database. ‘ sing connect method by passing the above URL. Inside this ie “myStudents”. Cay . MongoDB by means of hostname(locathosy B is running (27017). This is a path at which We arg Poy 3) Then we are u funey tion database object is created by a database nam 4 it is necessary to i Note that before execution of the above code, it ss ; ry to install the hn package using the following command at the current working directory. Prompt: >npm install mongodb Review Question 1. What are the steps to connect Node,js with MongoDB ? EB) Understanding the Objects Used in MongoDB Node,js Driver The MongoDBClient The MongoDBClient object provides interactions to connect 10 the database, Foon are some commonly used method of MongoDBClient object Method Purpose conneet(urloptions) | This method is used to connect to the MongoDB using the specified ul close(force, callback) | This method closes the db and underlying connections. db(dbname, options) Ttcreates a new DB instance sharing the current socket connections, isConnected(options) | It checks if MongoClient is connected. The db object The db object is created for connecting to the database in MongoDB. Following are some commonly used methods of db object - Method addUser(username, password, callback) Purpose It adds user to the database, admin() This method returns Admin db instance, collection(name, options, callback) Fetch a specific collection. The name is a collection name We wish to access, The eallback function accep!s - 1 stack Web Development pull ee MONGO DB ns,callbacks ) This method fetches all the collections for current db. Collections (oPtio This ft is method is used to create a new collection on a create! Se options.callbac ) Server with the specified options. Gropcollection(names options, callback) | It drops the collection from the database, removing it permanently, jaicollections( filter, options) This method is used to get the list of all the collection information for the specified db. xplain the MongoDBClient object and the methods associated with it. Explain the db object and the methods associated with it. 1. 2. po Simple Applications In this section we will discuss basic CRUD operations on MongoDB. CRUD stands for Create, Read, Update and Delete. The CRUD operations are performed in collaboration with Node,js and MongoDB. Prerequisite : For performing these operations we need to have MongoDB installed in our machine. One must also install’ MongoDB Compass (It is a graphical tool) to verify the operations performed by node,js on MongoDB. Example Code : In this example, we will create a Student database with two fields - name and city. 4) Creation of collection Step 1: We will create a database studentDB. For that purpose make a folder in your current working directory. I have created the folder by a name StudentDBDemo. Step 2 : Open the command prompt go to the path of StudentDBDemo. And issue the commands D.\NodeJSExamples\StudentDBDemo>npm init And press enter key to accept the default values. By this package.json file gets created. Step 3: Then install the mongodb module using following command D:\NodeJSExamples\StudentDBDemo>npm install mongodb Step 4 : Now create a node,js file for creating a database and collection. The code is as follows - (mongodb’).MongoClient; TECHNICAL PUBLICATIONS® - an up-thrust for knowledge Full Stack Web Development _ goaby 7700127017: url = ‘mon, ee siont(u!l): const client = new MongoC! //,Connect to the dabase const database = "studentsDB'; asyne function getData() { Use createCollection method to create a collection nameq student Info et result = await client.connect() Jet dbo = result.db(database); dbo.createCollection(‘Student Info); console log("Collection Created!!!) } getData(); Output TERMINAL PROBLEMS i) E:\NodeJSExamples\StudentDBDemo> Ue Mela eit Collection Created!!! Program Explanation : In above code, 1) First of all, we have to import the module ‘mongodb’ using require. Thus we are creating MongoDB client. 2) Then specify the URL for MongoDB by means of hostname (localhost or 127,00) and port number on which MongoDB is running (27017). This is a path at which ye are going to create a database. 3) Then we are using connect method by passing the above URL. Inside this function database object is created by a database name “studentsDB”. 4) Then using the method createCollection for database object we can create @ collection inside the database “studentsDB”. Note that here the collection names “Student_Info”. 5) The message “Collection Created!!!” is displayed on the console using console method. 2) Insertion of document oe the collection is created, we can insert some document into it. Following example code which shows how to insert one document into a collection named Student_Infe ‘sonst MongoClent = requir(moagodb iMengoGians) ct liaibad asst ae ATIONS® x Web Development _ , yy stack Web © eae ease MONGO DB *mongodb://127.0.0.1:27017 naan wie const client = new MongoClient(un); st en nect to the database | = "studentsDB" database = : const sync function getData() asi : result = await client.connect(); per gbo = result.db(database); ee mydata = {name:"Ankita’,city"Pune!}, gbo.collection('Student_ Info") nsertOne(mydata); console.log("Data Inserted"); } getData(); Output [sea OTL aco cdot TERMINAL 9 Ae aC earthen node insert. BS Ele Meta en| Program explanation : In above code, 1) First of all, we have to import the module ‘mongodb’ using require. Thus we are creating MongoDB client. 2) Then specify the URL for MongoDB by means of hostname(localhost) and port number on which MongoDB is running(27017). This is a path at which our database exists. 3) Then we are using connect method by passing the above URL. Inside this function a database object is created by a database name “studentDB”. Thus now we can access to studentDB 4) Then a JSON object is in the form {name:value}. We insert data in the collection in the form of document. This document is created in the form of JSON. Hence the mydata object is created with some values. 5) This mydata is inserted into the collection using insertOne method using following code dbo.collection(‘Student_Info').insertOne(mydata) In the same manner we can insert many documents in the collection TECHNICAL PUBLICATIONS® - an up-thrust for knowledge gf iy Full Stack Web Development __——~ ee Collection Y Inserting Multiple documents in he const MongoClient = require(mongod> const url = ‘mongodb//127.0.0.1:27017 const client = new MongoClient(ut)); // Connect to the dabase const database = 'studentsDB"; async function getData() R let result = await client.connect(); let dbo = result.db(database); var mydata = | { name: "BBB’, city: "Mumbai" }, { name: "CCC", city: ‘Chennai’ }, { name: DDD’, city: "Delhi }, { name: "EEE", city: "Ahmedabad’ } ii dbo.collection('Student_Info').insertMany(mydata); console.log("Multiple documents Inserted!!!"); } getData(); ) MongoCllient, Output ta aig eS A uusse.icatensinshe as node insertMany.js ST Ce eet emcee ne Program explanation : In above code We have created array of values in JSON object as Follows - Var mydata = | { name: "BBB’, city: Mumba‘ }, { name: "CCC, city: "Chennai" +5 Then using the insertMany command we can insert all the above documents at a time This program execution can be verified in MongoDB compass. stack Web Development 3-35 MONGO DB e pull open MongoDB Compass, just connect with mongodb://localhost:27017, select the gentDB database and then select Student_Info collection, The following screenshot Stu « multiple documents inserted into it, displays studentsDB.Student_Info 5 DOCUMEH Documents Aggregations Schema ExplainPlan Indexes __—Vallidation — Fite? Ov OED (& cron couscron) Taceroue: Aid: ObjectId("643£d162b6265487895e709' ) city ObjectId('6440dfdsabeaFecoeseabsbe! BBB" + "Mumbai" Multiple documents are inserted in the ObjectId (' 6440dfds4be9 fecoeSeabsbf) database. "cee" "Chennai" 2 ObjectId('64sedfasabe9feceSeabscO) 3) Displaying(Read) the data from Collection We can read all the documents of the collection using find method. Following is a simple Node.js code that shows how to read the contents of the database. Display.js const MongoClient = require(mongodb’)) MongoClient, Const url = “mongodb://127.0.0.1:27017;; Const client = new MongoClient(ur)); // Connect to the dabase ‘Sonst database = "studentsDB"; p Mai TECHNICAL PUBLICATIONS® - an up-thrust for knowledge 3-96 run Stack Web Development, jet result = await client.connect() let db = result.db(database): see let collection = db.collection(‘Student_n'’ . let response = await collection.find({})toAray() console log(response); } oe Output EES BeAr teu Ren es [ { BCH Object1d("643fd162b6265F487895e709")s fee etc { . met Han) Cy see Cacti tao es ona BoC Re rae Moet eat leo Pe De ra cons city: “Chennai* by { BPC Ren rae Cl Mencia tee Fy eee onsen ay iD i Program explanation : In above code, 4) First of all, we have to import the module ‘mongodb’ using require. Thus we are creating MongoDB client. 5) Th i e ) a specify the URL for MongoDB by means of hostname(localhost) and pot number on which MongoDB is running(27017). This is a path at which our database exists. cull stack Web Development 3 EE EEE ST SMe MONGO DB 6) Then we are using connect method by pas database object is created by a pee ssing the above URL. Inside this function a Ec scien € name “studentDB”. Thus now we can access 7) Then for reading the contents present in the doc i uN find() method. ments of the collection we use the 8) We use toArray method associated with the find() because it returns an array that contains all documents returned by the cursor 4) Update document We can modify the document using updateOne method, Following code illustrates it - uUpdate.js const MongoClient = require(’mongodb). MongoClient; const url = "mongodb;//127.0.0.1:2701 const client = new MongoClient(url); // Connect to the dabase const database = “studentsDB"; async function getData() { Jet result = await client.connect(); let dbo = result.db(database); var mydata = { name: "DDD"}; var newdata = {$set: {name:"TTT’,cit :Jaypur’}} dbo.collection('Student_Info") updateOne(mydata,newdata), console.log(One Document Updated!!!"); } getData(); Output Corbet) memes. TERMINAL PS E:\NodeJSExamples\StudentDBDemo> node update. js One Document Updated!!! 0 We can verify the above updation in MongoDB Compass. Just open the database StudentDB using MongoDB Compass to see the modification. TECHNICAL PUBLICATIONS® - an up-thrust for knowledge 3-38 i ‘Scheme _Explain Plan Full Stack Web Development. Docunients Agaregations Fite? @v Type a query: { field: ‘value’ } ECE | © Exrorr cot bjectId (' 6440dFd84be9fecbeseabsbe') Pineal : "Mumbai" |: ObjectId(' 644edfds4be9 f6ceeSeabsbf') Goce "chennai" ObjectId( "440d dB4beof6cde5eab6c0") Sap oe eis record is updated : ObjectId(*644edfd84be9f6c9eSeab6cl ') Bee "Ahmedabad" Program explanation : In above code, We are updating one document using updateOne method. This method require two parameter first one is the existing data and second one is the new data which you want to put in place of the existing one. This can be done with the help of following lines of code var mydata = {name:"DDD"}; //existing record with name = “DDD” var newdata = {$set: {name;"TTT’,city:"Jaypur’}} //replace it by a new data Then updateOne method is called by passing these two parameters. 5) Delete document This is the operation in which we are simply deleting the desired document. Here to delete a single record we have used deleteOne method. The code is as follows - deleteOne js 52 gee : stack Web Development 3-39 MONGO DB Fu a await client.connect(); result.db(database); jor result e myaata = (name: EOE “ document jete the ype o.collection( consolelog("One "Student_Info').deleteOne(mydata), Document Deletedi!"); b ita()i tal) get Output PROBLEMS fe Uiaus DEBUG CON Bias Pema ees Mee ane ea epee (Me een Ee Ponts Dorel itiee eee 0 We can verify it using MongoDB Compass. Note that the name “TTT” is missing. Ptr cae © EXPORT COLLECTION 0 Lid: ObjectId('643f6162b6265 4: » ! name: "Ankit city: "Pune Lid: ObjectId(' 644edfa8dbe9 f6cOeSeabsbe") id: ObjectId(‘614adfdaabesfoceeSeabsbf') ame: "CCC" city: "Chennai" 1: ObjectId( '6440dfd84be9 fecbeSeab6cl') name: "EEE city: “Ahmedabad” TECHNICAL PUBLICATIONS® - an up-thrust for knowledge: Feeerces | Sacha lay.js Ly BRC call free ee een ( oo ee ee car ca alee psec une" a PR Gee acca NS Baa Pe cnc cceaca ti can ere 6) Sorting documents Data can be arranged in sorted order in the collection. For displaying the sorted ong data we use the method sort. Following code illustrates how to display the data in Ascendin order of the filed named city. Sort.js const MongoGiient = require(mongodb).MongoClient; const url = “mongodb//127,0.0.1:27017", const client = new MongoClient(ur); // Connect to the dabase : const database = ‘studentsDB*, async function getData() { let result = await client.connect(); Jet db = result.db(database); let collection = db collection('Student_Info'); var mydata = {city:1); let response = await collection find({}).sort(mydata) toArray(); console log(response); } getData(); x Web Development ee a MONGO DB Me ee olsen Westie Ceo reer ys BB", : Te Dee CS Gace cry Stee Program explanation : In above code to sort in ascending order we use sort. The key field based on which the document is to be sorted is i We have passed | along with it for displaying the city names in ascending order. If we pass -1 then the cities are displayed in descending order. Simply change the above code as var mydata = { city: -1}; J. Explain insertion and deletion database operation using NodeJs. 2. Write a program to display the sorted data in the database using NodeJs, 3. What is CRUD ? Explain the CRUD operations in node.js. ERE Advanced MongopB Following are the features of advanced MongoDB. 13.11.41 | Indexing For efficient execution of queries the indexing is used. If we use the query without indexes then the execution of that query will be very slow. Definition of index : Index is a special data structure that store small part of collection’s data in such a way that we can use it in querying. TECHNICAL PUBLICATIONS® - an up-thrust for knowledge 3-42 Full Stack Web Development “The index store the values of index fields outside the table or coletion ang ye their location in the disk. <0 troy | Demonstration : oy | 1 In order to create an index, we will use the database named mystudent, Ty | Student_details will be used for creating index. a “leg, 1) Index creation Syntax for creating index is db..createIndex({KEY:1}) The key determines the field on. the basis of which the index is created. After the eo oe 5 y direction of the key(1 or -1) is used to indicate ascending or descending order. ee The MongoDB will generate index names by concatenating the indexed keys with the direction of each key with underscore as separator. For example if the index is on the field name and the order as 1 then the index will be created as name_1. We can also use name option to define custom index name while creating the index. For example - > db Student_details.createIndex( {name!1}, {name:'Student's Names'} ) The result will be as follows - BB Command Prompt - meng > do, tudent_details.cresteIndex( (nae-1), (name:“Student’s Nemes") ) “ereatedCollectionsutomatically” : false, “mumindexesdefore” : 2, “rumtndexesafter® = 3, “oe sia Web Develoenet ots MONGO DB a ayrind cocina end all the available indexes i we cam fin Xes in the MongoDB by using getIndexes method. | gyntax Zeoiiection”” r example - ent_details.getIndexes() igotindexes() Fo! ape 108 Cor ap stude Note that the output contains the default_id index and user created index. 3) Drop index To delete an index we use dropIndex method. Syntax db Zcollection > dropIndex(Index Name) For example db.Student_details.dropIndex("Student's Names") The result will be Command Prompt -mongo 4b, Student_details. dropindex(“student’s Names") ‘iindexeswas” : 2, “ok” 4) Compound index We can create index on multiple fields in MongoD! {name:t, age:-1}) TECHNICAL PUBLICATIONS® - an up-thrust for knowledge B document. For example 3-44 Full Stack Web Development F Mor, It will sort by name in ascending order and age 1" descending order. If the Nameg an x then the descending order of age can be noticed. re % 1 3.11.2] Aggregation Ageregation is an operation used to process the data that results the computeg ree aggregation groups the data from multiple Oe and operate on grouped data fe S, : combined result. The MongoDB aggregation is equivalent to count(*) and with ene Bet sql. MongoDB supports the concept of aggregation framework. The typical beet Y iy aggregation framework is as follows - Ne op Output Fig. 3.11.1 Aggregation framework 1) Smatch() stage - Filters those documents we need to work with, those that cee needs. I 2) Sgroup() stage - Does the aggregation job. | 3) Ssort() stage - Sorts the resulting documents the way we require (ascending i. descending). The input of the pipeline can be one or several collections. The pipeline then successive transformations on the data and the result is obtained. Syntax for aggregate operation db.collection_name.aggregate(aggregate_operation) Performs Demo example For demonstration purpose, I have created a database named CustomerDB inside which there is a collection document named customers. Some data is already inserted into it. The contents of customers document are as shown below - [eames b use CustomerDs switched to db Customerd8 > db. customers. Find() a Object1d(“61e57c1128e95223b716Fcf"), “name” = Ob ject Id(~610e57#128e952236716fd0"), “name” ObjectId(“61¢e5834128¢952236716Fd1"). “name” + ObjectId("61@e585c128e952236716fd2"). “name” Object1d(~610e5874128e952236716f43"), “nome” - “Developer” } “Tester” } “Tester” } veloper” } “Developer” } evelopment 346 ee ee ee onel su gsue the following command 0 tte([{Sgroup : { id: . , _gesarsoaeoastel aro% (ii $type’ categoria HSV) “enna rom men9 vers ageregate([(SErOUp : (id? “$type*) category: 35. cos oes Teper, “category”; 3) he” CARER: (Ssum = 3y))1) wrester", “category” : 2} | | | I | The above command will display total categories of the customers - In our database there two types of customers - “Developer” and “Tester”. There are 3 developers and 2 testers in the collection document. The aggregate function is applied on the $group. similarly if we want to find only Developers from the collection document customers then we use $match for aggregate function. The demonstration is as follows - [pi command Prompt - mongo erry |, db.custoners-cgeregate([(Seatch = (type:"Developer"}}1) E iar; ObjectId("610e57c1128e952236716Fc: ig Gd"; Ob jectId("610e585c128952236716F42"), jar + Object Td("610e5874128e952236716643"), “name” : "EEE", “type” “Developer” } Expressions used by aggregate function Expression Description Ssum | Summates the defined values from all the documents in a collection Savg | Calculates the average values from all the documents in a collection Smin Return the minimum ofall values of documents in a collection Smax Return the maximum ofall values of documents in a collection SaddToSet | Inserts values to an array but no duplicates in the resulting document Spush Inserts values to an array in the resulting document Sfirst Returns the first document from the source document _ Slast Returns the last document from the source document ‘PUBLICATIONS® - an up-thrust for knowledge Ful Stack Web Development ex —~Moy EJ Map Reduce Keane Map reduce is a data processing programming model that helps in Performin on large data sets and produce aggregate results. Pera Map reduce is used for large volume of data. The syntax for map reduce is >db collection. mapReduce( fanction() {emit(key,value);}, < map function function(key,values) {return reduceFunction}, { < reduce function ‘out: collection, — the collection is created in which the result of mapReduce can query: document, Storeg ‘sort: document, | limit: number | B | ) - ; Where 1) map Function : It uses emit( function in which it takes two parameters ke } key. Here the key is on which we make groups(such as group by name, or second parameter is on which aggregation is performed like avg(), on. Y and vay. | z Be) and i, | SUm( is calculagg 2) reduce Function : This is a function in which we perform aggregate function avg(), sum() . 3) out : It will specify the collection name where the result will be stored. | 4) query : We will pass the query to filter the resultset. 5) sort : It specifies the optional sort criteria. 6) limit : It specifies the optional maximum number of documents to be returned. Demo Example : | Step 1 : Create a collection inside the database mystudents. The collection is created using name Student_info. i {3 Command Prompt - mongo > use mystudents witched to db mystudents > db.createCollection("Student_info") SOkM ati} eb Development 3-47 a’, marks:74}, :Kavit marks:86 } Fan Prt noe info. Find()- pretty) 4—Issue this command to display the documents inthe collection = 4g” + oojecttd( s1iecezassoesezeze7fecn"), | en nada, parts: 96 ) char + opjectta(“e1secezassonsenaaertac), Tite Sindee, Slane: 36 object14("6i1eceza8sessezd2e7fac24"), wankita’, 1eceza8sonse2d2e7f4c25"), ob jectId(“6110ce2a85089e242¢7F4c26"), vite”, 41850890242¢7F4c27"), Step 3 : Now we will apply mapReduce function 1 Command Prom - monge > var map = function() { emit(this.nane,this.marks > var reduce = function(name,marks) {return Array.sum(marks);}; t > db.Student_info.mapReduce( mp, LAE Pass both the ‘map! Create a ‘map’ function which stored name and marks fields Create a ‘reduce’ function that reduce ees and ‘reduce’ finds the sum of eee functions to all the marks of Sresult” : "Result", “ok” : 1} mapReduce and each student create a collection named "Result". PUBLICATIONS® - an-up-thrust for knowledge 3-48 Full Stack Web Development Mere. “eo, a be seen with help of fing et Step 4: The output of the mapReduce can Ore we illustrated by following screenshot - . }) HE Command Prompt - mongo > db. Result. find().pretty() KC Sig": “ankita’, “value” : 274 } I{ "Lig" : “Kavita”, “value” : 247 } Advantages of mapReduce 1) MapReduce allows the developer to store complex result in separate Collection, 2) MapReduce provides the tools to create incremental aggregation over large eo) 3) It is flexible. Bet ony J. List and explain the features of advanced MongoDB. lection: 2. What is the purpose of mapReduce. Explain it with suitable example. £4 Two Marks Questions with Answers. | Q.1 What is NoSQL ? ea | Ans. : NoSQU stands for not only SQL. It is nontabular database system that store dat differently than relational tables, There are various types of NoSQL databases such as i} document, key-value, wide column and graph. Using NoSQL we can maintain flexible schemas and these schemas can be scaled easily with large amount of data, Q.2 Enlist the features of NoSQL, Ans. : 1) The NoSQL does not follow any relational model, definition of schema, 3) Multiple NoSQL databases can be executed in distributed fashion. 4) It can process both unstructured and semi-structured data, 5) The NoSQL have higher’ scalability. BE qane features of MongoDB. lis 03 ment é web Developiit a ee MONGO DB document based database system. ye ie Fc high performance data persistence. 2). Tupte a multiple storage engines. 3) F . arich query language support. ) ongoDB provides high ayailability and redundancy with the help of replication. 2) That means it creates multiple copies of the data and sends these copies to a different server spat ifone server fails, then the data is retrieved from another server. e, How the terms in MongoDB are different from SQL ? eg The terms in SQL are treated differently in MongoDB. In MongoDB the data is not gored it tables, instead of that, the there is a concept called collection which is analogous to the tables. In the same manner the rows in RDBMS are called documents in MongoDB, likewise the columns of the record in RDBMS are called fields. qs Explain the createUser command in MongoDB. Ans.: The user accounts are created using the createUser() method. stax |db.createUser(user, writeConcern) Parameters user : Is a document with authentication and access information about the user to create. writeConcern : This document represents the level of write concern for creation operation. Q.6 How remove users from MongoDB ? ‘Ans. : For removing the user, the db.dropUser() is used. Syntax \db.dropUser(usern-me) Q.7 Enlist any four data types in MongoDB. Ans. : Following are various types of data types supported by MongoDB. 1) Integer : This data type is used for storing the numerical value 2) Boolean : This data type is used for implementing the Boolean values i.e. true or false 3) Double : Double is used for storing floating point data. 4) String : This is the most commonly used data type used for storing the string values. Ei: ) Min/Max keys : This data type is used to compare a value against the lowest or highest BSON element. TECHNICAL PUBLICATIONS® - an Up-thrust for knowledge 3-50 an eS aaa ten : a 3 i tiple values in one key, thi NG 6) Arrays : For storing an array of list of multip! y, this data i - 24 ed. lain how to create collection in MomgoDB ? Q.8 Expl ‘Ans. ; After creating some sample database we must create some collection Sid database. de thy We can create collection explicitly using createCollection command. Syntax /db.createCollection(name,options) where name is the name of collection options is an optional field. This field is used to specify some parameters such as siz, e, maximum number of documents and so on. Q.9 How to insert multiple documents in a MongoDB database ? Ans. ; It is possible to insert multiple documents at a time using a single command. Folk command shows how to insert multiple documents in the existing collection, a > var = allStudents = { { "name": AAA, "age": 20 } i "name": BBB, “age':21 } { "name": CCC, "age': 22 h I >db Student _details.insert(allStudents); Q.10 Explain the MongoDBClient in detail. Ans. : The MongoDBClient object provides interactions to connéct to the database. Following | are some commonly used method of MongoDBClient object. Method Purpose connect(url,options) This method is used to connect to the MongoDB using the specifi close(force, callback) | This method closes the db and underlying connections. ed uth x Web pevelopment 3-51 MONGO DB It creates a ne wDI B instance sharing the eurreni socket connections. It checks if MongoClient Is connected. what is Map reduce ? 4 ce is a data proce: . Map reduce ii Pp Ssing programming model that helps in performing operations ge data sets and produce aggregate results, sap reauuce is used fr AFB VolUme of ata, The syntax for map reduce is siiection- mapReduce( a) {emit(key,value);}, <-map function rjonckoy.values) {return reduceFunction}, { <-reduce function put: eoection <-the collection is created in which the result of mapReduce can be stored er’! document, on lant ab: post: aooument mit; momber i ) Where 1) map function : It uses emit() function in which it takes two parameters key and value key. hich we make groups(such as group by name, or age) and the second Here the key is on parameter is on which aggregation is performed like avg(), sum() is calculated on. 2) reduce function : This is a function in which we perform aggregate functions like avg(), sum() 3) out : It will specify the collection name where the result will be stored. 4) query : We will pass the query to filter the resultset. 5) sort : It specifies the optional sort criteria 6) limit : It specifies the optional maximum number of documents to be returned. Q00 TECHNICAL PUBLICATIONS® - an up-thrust for knowledge

You might also like