0% found this document useful (0 votes)
80 views35 pages

Unit 3-1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
80 views35 pages

Unit 3-1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
UNIT Ill MONGO DB ‘Syllabus rand NoSQL and MongoDB - Building MongoDB Environment - User accounts - Access a eatin ving databases - Managing collections = Connecting to MongoDB from Node,js - Und co simple ap Contents 31 Understanding NoSQL and MongoDB 32. Building MongoDB Environment 33 User Accounts Access Control 3.5 Data Types in MongoDB 3.6 Administering Databases 37 Managing Collections DB from Node.js 38 Connecting to Mongo! ts Used in MongoDB Node,js Driver 39 Understanding the Object 3.10. Simple Applications 3.11 Advanced MongoDB 212. Two Marks Questions with Answers (3-1) Need: Features : © The first read; i @ Weigh Si Mongo ois relenscd 3 ed in March 2010. pl understanding Nosol NosaL ob. i ands for not only SQ" « data differently than relational ele h as document, key-value, wide colum are various types OF graph. and these schemas can be scaled e; «Using NoSQL we oa maintai with large amount of data. in flexible schemas ‘The NoSQL database technology is usually adopted for following reasons - a 1) The NoSQL databases are often used for handling pig data as a part of funda architecture. 5 2) The NoSQL databases are used for storing and modelling structured, semi-structt 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. : 1) The NoSQL does not follow any relational model. 2) It is either schema free or have relaxes i i .d schema. That means it does not require specific 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. ‘ 6) Itis cost effective. 7) It supports the data in the form of key-value pair, wi pair, wide columns and MongoDB ee MongoDB is an open source, It is developed and sup document based database. MongoDB Inc. ported bs 'y a company named 10gen which is now known # TECHNICAL PUBLICATIONS® - wry need flex _ feb Development soot a 3-3 MONGO DB why mongoDB is needed ? ‘There ae ee et RDBMS products available in the market, then why do we ced Mongo) } all the moder applications require Big data, faster development and ible deployment. This need is satisfied by the document based database like MongoDB. res of MongoDB flex! Feat 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. SQL Terms. [vensooe Terms | >_> Fig. 3.1.4 * Consider a student database as follows - TECHNICAL ‘PUBLIGATIONS® - an up-thrust for knowledge Full Stack Web Development. 3-4 MONGo dg To the left hand side we show the database in the form of table and to the right hang side ° z the database is shown in the form of collection. Collection t id':527f191e810c19349de860eg, ‘Name''Ankita’, : "Course’Computer Engineering’, “Address"{ Document ‘linet"’Lane1" ‘Vine2""Lane2* } he * id65711910810019729de8600, Name| Course | AddressLinet] Addresstinez] | Giurvermoitee Computer Lari eae “Course""Mechanical Engineering’, : Ankita Engineering ane = "Address":{ ‘Document 2 i ‘ine1"'Stroot?", Gaal Mechanical : Preiktal Engineering | Streett Street2 "mez See Cll Kavita} Engineering | Road Road2 , * id":60711410510c19729dey60ed, + WName"Kavita’, Fields "Course"'Civil Engineering’, + tadaress( Document 3 ‘line1""Roadt", Fig. 3.1.2 Review Que: 1. [for it ? Enlist various Seature of NoSQL. 2. List and explain various features of MongoDB Ey Building MongoDB Environment For installing the MongoDB 0 to the web site hs:/w.mongodb.comtry/download/eommunity Choose Software->Com: Run to execute it, munity Server. The executable file gets downloaded. Click on put tack Web Development il SU MONGO DB Open File - Security Warning Bo you want to run this tite? FAHD _Name: cads\mongodb-windows-186,64-605-signedmsi ~~ Publisher: MONGoDB, IN, Type: Windows installer Package From: C\Users\DELL\Downloads\mongodb-windows-r8.- White files from the Internet can be useful, this file type can Potentially harm your computer, Only tun software from Publishers you trust. What's the risk? Welcome to the MongoDB 6.0.5 2008R2Plus SSL (64 bit) Setup Wizard The Setup Ward wnt Mongon8 6.0.5 208R2F SL (Gn by on your computer, Cc et to canine oc Coes fot the Setup Wizard i i ‘ion. Follow the ete option for installation. i and choose the Comp! eh de vee oi ee by clicking the Next button. If you do not va tis Sonne procedure write Graphical tool of MongoDB), then simply uncheck the option. longoDB Compass Finall will get following window on successful installation. Finally you fo ke A _ pus Ss (64 Dit SETUP Tra Monged8 605 2008R2) Completed the MongoDB, 6.0.5 2008R2Plus cextte Fach to 0 tbe Sten WES Click on Finish button, to complete the installation process. In order to verify whether it is installed correctly or not, go to command prompt S| and execute the command for mogod.exe file’s version. It is illustrated as follows - Windowssstensbiende X Nicrosoft Mindons [Version 10.0.22621.1555] €:\Progran Fies\tongo\serves\6.0\bin>aonged Ave —vers db version v6.0.5 a ie Build ee: f wersan: 0.0.0", “pitlerstonet aabpe “Berio Sesbctnimcaneszcbnstastaseetdie" “aitscatss Secnatoce wéizteod":Suindons ndistarch*: "x86_6u"’ earget aschs oe bu \Progran Files\HongoDB\Server\6.0\bin> To set the envirom iment vari: Variables ‘ble, Open System Properties and SSL (64 bit) Setup Wizard = 1 : ( If the MongobB is correctly installed {then you will get this click on Environment pul sack Web Development 3 7 MONGO DB ‘System Properties Computer Name “Hardware Advanced System | System Protecto ‘Yourmustbe logged ato ice Jonas an Administrator easel lo make mostofthese changes, Visual eects, processor scheduling memory usage, and vital memory a ay User Profiles Desktop setings relatedio your signin Statup and Recovery } System stamp sytem au, and debugging inamafor CCAUsers\DELLVAppDataloca\ Temp system variables ee | [variate : Value || chocolateylstall ‘caprogramData\chocolatey s classpath ‘caProgram FilesVava\j 180.1biehms ot tema2\emaene | | comspec cawindowsrsyst DriverData Ccawindowes\system32\Daiverss¥eF0302 JAVA. HOME ‘caprogram Files\ava\jake15 04 NUMBER_OF PROCESSORS 8 os. Windows NT Os ns: ant Variables “perverts fra E Verabie —atue | chocolateyLastPathUpdate | 132550151847677214 | lesen ela rte. eycometer oS | oneove QDeOLNee FP eeereeconsumer | __ eAVADELNOREDe oe Reson acanntoth WedwaaeesCU ut tack Web Development User Accounts MONGO DB MongoDB stores the informati MongoDB . mation of all the users includi authentication in the system, ing name, password and user using MongoDB shell comm: : and we can create the user accounts, Usin h we can read and write to the databases, : Ce ‘The most commonly used operations are 1. List the users v . Create the user accounts 3. Remove the users Let us discuss them one by one. EEG Listing 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. i mongosh mongodb://127.0.0. X test>. use admin switched to db admin admin> show users 0 admin> admin> As no user is created, it is showing empty find). The db.system.users- ber oF Al find() returns a cursor object. Then heer in the system. For using count() ae we can obtain the total nu f users present i ys example = ERY create User Accounts 1() method. ser accounts are created using the createUser(Q) The us syntax - db.createUser(user, writeConcern) Parameters The user document has following fields [Name Description | user The name of the new user. pwd. The user's password. The pwd field is not required if we tun db.createUser() on the Sexternal database to create users who have credentials Stored externally to MongoDB. customData Any : id be the user’s full name or employee id. The rol a er. Ci to create users without roles, py sack Web Dovelopment ‘me role can be specified as wien a8 joe OOP bE Saba For example - HB mongosh mongoab:27.0¢ admin> use test | switched to db test | test> db. createUser( user: "Parth", pwd: "Parth123" roles: [] : 3 |... | { oki¢1} Now to test, if the user named Parth is created or not, we issue the show users command atthe MongoDB shell. fa mongosh mongodb://127.0.0. test> show users C { \ a Re 5 ot Rs wun ‘gghb3031-F90F-Hdle-9749-BoiueseHeois Ve | user: ‘Parth’, +SCRAH-SHA-256' 1 [ {SCRAM-SHA-L'. igs during eu jgn the role to the user The ab ated without any role. But we can ass! le above user is cre the he createUser command. ae ee ead AnyDatabase readWrite d from and write to the act, get statistics profile’ ows the user to reat ‘This role al fy, comp: as well as clean, modi dations. dbAdmin perform vali Same as dbAdmin except for all databases. dbAdminAnyDatabase and modify user accounis This role allows the user to create the database. ‘Same as userAdmin except on the local and config datat vuserAdmin ‘serAdminAnyDatabase For example - db.createUser( { user: "sysAdmin", pwd: "pass123", roles:['readWrite’,"dbAdmin'] } ¥ Follow’ shot represents how to creat with role. ‘ing screen: presents how to create user with rol “sysAdnin! passizan, | ~ roles: [readily ite” "dbAdmin™] jack Web Development 3-17 Remove Users yor wmoving the user, the db.dr .dropUser() i isu ntax © gp.dropUser(username) ror example ga mongosh mongodb://127.0.0, x test> db.dropUser("sys A { ok: } sysAdmin test> By above command the user named “sysadmin” is removed. [ie eS explain various roles of the Explain how to create user in MongoDB ? Also enlist and awsers. 2. How will you remove the us er in MongoDB ? Explain. EJ Access Control ontext of a sing! ation and jatabase level. on purposes, MongoD! * User exists in ¢ Je database. MongoDB provides authentica authorization at a collection + For basic authenticati B stores user credentials inside | called system.users in each database. * The admin database does not have any users as nt provides the abili signed to it. ty to create user accounts in the admin * The User administrator acco and other databases. Ra Creating a User Administ ecess contro: rator Account 1, the first step is to impl ement User Adm * For configuring the & account. — ATIONS® - an Up- rust for knowledg® 3-18 create and assigns roles. A User Adm ult 208 ni ‘an create new OneS: ; ne and o fax rministrator as the first user mini ‘i tabase User Adi riege 8 Oe User Ad jase admin db createUser( { user” ") Roles: roserAdminAnyDatabase)) For example Ta engxh engoszuaT 00. test> use adain Creating admin user in ee decals the admin datababase 323") “AdsnanyDatabese"1}) Displaying the users from the admin “ad: ‘admin. sysadmin’, — dgertd: new UUIOC*bsadbedé-ttea-osd-B7de-UeedeaTd4611") user: ‘sysat ie = abi fade", fetes: UU role: “ucerkas lato : mechanisms: [ 'SCRAM-SHA- *SCRAH- ot tadnint 31, J Note that the administrat i lor user Is Now sys; i i We can authenticate the admin datab; cine Rardin re password options. For example - ase using db.auth command with user na ‘ongosh mongedki/cerede 5 | test> use admin switched to db admin Sysadmin” systen123"), i or: "Passi23n). cal Authentication fate, account the createUser method is used. The assign » dbAdminAnyDatabs . For example - 'yDatabase, clusterAdmin. switched to db admin admin> db.createUser( “dbAdmin", assword123", [read¥riteAnyDatabase™ , "dbAdninAnyDatabase” clusterAdnin"] We can use this user in MongoDB shell to administer the database. |. Explain with suitable example how MongoDB ? to create database administrator account in Woata Types in MongoDB es of data types supportec type is used for storing the ype is used for impleme d by MongoDB. numerical value. nting the Boolean values i.e. true or Following are various typ 1) Integer : This data t 2) Boolean : This data t false. _ raat for krone - “anal PUBLIGATIONS® en ups — TEC! nt data. pe used for storing th a se alee ae ‘fo che are a value against the velapmen ating pol puss DDO tl for storing floating Po" ssed to COMP! F wi veys 2'Tnis dale type is Us 5) in! 's MINN BSONEEEHET ets cr multipte values i one key, thigh daa Ri 6) Arrays ded documents. emented for ember sua type. This data type is used O18 oct is imple 3 type is similar © string da specie sy j 9) _ Null : For storing the ru values this data {PE IS used. used fo Sore current date or time. We can also cre (2) Dist 10) Date : This data type is own date or time object In order to store binary data we need to use this data type. ed to store regular expression, 11) Binary data 12) Regular expression ¢ 1. Give various data types used in MongoDB. al ‘This data type is U EJ Administering Databases uss how to create and-handle database in a In this section we will di various commands. (1) Create Database Open the command prompt and typ. ‘ommand mongos! starting the mor and ompt and type the commar ngosh fe ong sh for starting shell. The test> romp Ww sree ay (OS Prompt will appear. For creating ad ating a database we 2 need to. use the ‘Syntax use Database name For example No not in show (3) Dr TI rorgos mongeea ar "mag. x test> us e nystudents switched to nystudentss “© "Students 7 'ECHNCAL Bugis sack Web Development To check the currently selected databag, os MONGO DB. €, Use the cor mm: Sa mongeth monsoabdnztag wand db lievseseene eae Pans | aystudents nystudents> (2) Displaying all the databases present in the system We can see the list of databases present in the MongoDB using the command show dbs For example - nystudents> show dbs adnin 180.00 KiB eenfig 72,08 Ki Local, 72,00 Hie | nystudents> Note that in above listing we can not see the mystudents database. This is because we have not inserted any document into it. To get the name of the database in the listing by means of show command, there should be some record present in the database, (8) Drop Database The dropDatabase() command is used to delete the database. For example - Tid. mongosh mengod/r2700. * poatabase() nystudents> db.droy ee Taystudents' Lok: 1, dropped: nystudents> at for krone Trepp PUBLICATIONS® an pat re? oe ate some collection inside that dat tae fete and update on this collection, Thy Create, Read, Update and’ operations are ca operations. 4) Create Collection ion command. i reateCollectio We can create collectior n explicitly using ¢1 syntax ‘gp ereateCollection(name,options) where name is the name of collection options is an optional field. This field is used to specify some parameters such as) 3)i maximum number of documents and so on. ¥ ; Following isa list of such options. [Field Type Description the capped Boolean | Capped collection isa fixed size collection. It automatically sy overwrites the oldest entries when it reaches to maximum size. Iti a is set to true, enabled a capped collection. When you specify this : ‘ value as true, you need to specify the size parameter. autoindexID | Boolean | This field is required to create index id automatically. Its defatlt value is false. size Number This value indi : icates the fc oe maximum size in bytes for a clapped Max Number It specifies the ma: : collection, ‘ximum number of documents allowed in CaP For example - Followi vin explicit command '@ command shows how to create collection in a database Us c co ae text> use nystudents pitched to db wyStudents | States? eb createcotteetion(» nyStudents> "Student _detaitery ) I i i _y sock Web Development e- 3-23 1 oispl2¥ Collection To check the created collection use MONGO DB the command “s and “show collections” at the command f mongosh mongodb://127.0., a | myStudents> show ci : | student_details ‘oLlections i | myStudents> 1 { prompt | | | | 3) Drop Collection The drop collection command is actually used to remove the collection completely from the database. The drop command removes a collection completely from database. syntax abcollection name.drop() For example WI mongosh mongodb//127.0.0. * myStudents> db _student_details.drop(); myStudents> » in the database. collection by using “show collections We can verify the deletion of the a x in mengodb:/127 0. a ngs! ions collection: ts> show yystuden | aystudents? ithin the collection 4) Insert documents wi —— The document is inserted within the collection. The document is analogs database. Syntax db collection name insert({key,value} For example BI mongosh mongodb:/N27.00. x myStudents> show collections myStudents> db.createCollect tok: 1} pStudents> db. Student_details.insert({" ‘don("Student_details" name! AAA" "age": 223) acknowledged: i insertedids: { '0': ObjectId("6u3eub6343697309a1a2a66") 3 | nyStudents> We can verify hi j © can verify this insertion by issuing following command ha ——————_—_—_——_—_— sexx ed Development fl B_mongosh mongedbinzran 5¢ = MONGO DB nyStudents> aan baseeStudent detains 65 fystudentes tra" SHBeubezusciorsoe 399, 182866"); nase: i ie: "AAA + age: ginserting Multiple Documents ris possible to insert multi cum ti ereenshot shows how to insert bee = Sa e e unne 8 sit wultiple documents in the existi al ae aa ‘ing collection. ong egod 37 myStudent> var attstucent: f ] 2s. name! sranb>, ‘age: yyStudents> db, Student_details-insert atlstudents) ; acknowledged: irr, insertedids: { rs objectId("6uze518d436U97399a1a2067- it) objecttdc-e43e510d436u97399:2a2860°) tion you can use find command as of these documents in the colle ; To verify the existence falloy Tt mongosh mongsub/27.00. nyStudents> db Student details: Find C { id qpjectracnou3eude3tne4973090122265,}+ name id Ob sec crae51 843619739985 02 3) name: id op aecerd("6izeS18d43649720902* | name 'AAA', age "Bes", age §p, elete Dos cuments ; 7 mmand is used. This is the simplest command. F 3 °r deleting the document the remove 0) FEGHNIGAL PUBLICATIONS® - 27 UP rarust for knowiedg® — student detaits.FndO 1a2a66"), ' I) aystudents™ te a record with name ppp” we can issue the command as follows - Now to del Te rongosh mongocesna720. X isyStudents> db.Student.details deletedne({"nane” Packnontedged: ‘ur, detetedCount: nyStudents? Now using find() command we can verify if the desired data is deleted or not. a rongonr menos: nyStudents> db, Student details. Find() “id: Object 1d("643eub63436N97399a1a266"), name Russ Object 1a("6u3e5186436U97399a1a2a67"), name. nyStudents> TARA', age “BEB, age: 7) Delete All Documents nyStudents> db. stud ‘udent_detai { acknonledged: sietaits detetel nyStudents> + deletedcount Hany C4} wy We can verif a y it using db.Stude are deleted or not, ae It MONGO DB. myStudents> db. studene deta -detaits, | mystudente> yt qponlection_name.update (criteria update zh *adata) For example Suppose the collection “sr, “Sf 5 udent_details” contain following documents mongosh mongodii279a. ayStudents> db. Student_details.Find() orc tran ject Id("643e73b2436U97399a1a2a6c"), as ‘a rongesh mongade/72r.00. % nyStudents> db. Student _details-update{*nane" :*CCC*) {5 renee tfarwarning: Collection update) is deprecated. Use updateOne, updateRany, or bulldirdte. { acknowledged: | mongosn mongod//27.00 jetaits. find) Object 3697399412860) . ed bec re raynaeNsT IOI Ths the document gets updated: _ ort for rowed + MC ment cn i. Full Stack Web Develop! nd updates @ single document, But we can upd late By default the update ae Sa vas} . For that purp' ‘ documents as well. ‘ For example @piSudent details update({"age 9) Sorting We can use the order based on particul t() method for arranging the documents in ascending or des, sort lar field of document. ‘Syntax ; For displaying the documents in ascending order we should pass value 1 ‘ab.collection name.find().sort({field_name:1}) oe : Ifwe pass -1 then the document will be displayed in the descending order of the field For example Suppose the collection contains following documents. ObjectId("6u3e72de436497399a1a2a69"), ObjectId("643e73b2436497399a1a2a6a"), ObjectId("643e73b2436497399ala2a6b") , + ObjectId("6U3e73b2U36U97399ala2a6c"), fyStudents> ‘db. Student_details. Find(), sort({*age":-1}) { Ad: objectrd¢"6uze73b24364973 { ObjectId(6u3e72deu364973, : wid: Objecttd("643e73b24364973 | | ~*#? SbJecttdc*6uze73b2u36u97a99a1 sane" nyStudents> 99alada6e"), name: 99a1a2a69")| name: 99ala2a6b")| name: order We issue following command -find().sort((agaltijy aS gs ; Web Development Connecting to MongoDB from re MONGO DB lode.js or connecting the Node. -i8 with Mon; 1oDB galiowing are the steps used to connect PB we we MengoCtnt le js with MongoDB, + Install MongoDB dri yep 1? river sept for Nodes by issuing foll pam g following command on the command apminstall mongodb 2: In the Node.js application program require t oDB module by adding folloy er squire the Mong by addi ce const MongoClient = Toqiulne(mongoasy) ‘MongoClier i nt; gop 3: Define MongoDB Connection URL ost ul = "mongodb //127.0,0.1:27017/mystudents' step 4 : Create the instance of MongoClient by passing the above URL to it Itis as follows - const client = new MongoCiient(url); step 5 : Finally use the connect method to get connected with the database iont.connect() - The complete code is as follows - App js jigotthe mongoDB client const MongoClient = require(mongodb) MongeCiients IiSpecfy the URL of the database to which the ‘connection is to be done const url = "mongodb://127.0, (0.1:27017/myStadents"; JiCreate client instance const cient = new MongoClient(un); (Connect to the database function getData() { client,connect() then(()=>consoleloa( catch(error=> console lout Fale » "connected to Database successfully!"")) ‘4 to Connect’errer)) getData(); per a er te Pe Aaa kid eo Petia md : yee hea Ee ioc fran eet ert) vast or knoe ea rimson08s pant ort Te Diocese recuu, Full Stack Web Development ion: re code, ey Merlo tne tyne RS la lg 8 aa creating MongoDB client. 2) Then specify the URL for MonigoDB by means of hostname(loca ‘number on which MongoDB is running (27017). This is a path at whi to create a database. host) ich We ate 3) Then we are using connect method by passing the above URL, Inside this fun database object is created by a database name “myStudents”. Note that before execution of the above code, it is necessa Package using the following command at the current working direct 'Prompt:>npm install mongodb * Been 1. ry to install the Mong tory. What are the steps to connect Node,js with MongoDB ? ee 13.9] Understanding the Objects Used in MongoDB Nodejs Driver : The MongoDBClient The MongoDBClient object provides interactions are some commonly used method of MongoDBClient of Method connect(url,options) to connect to the database, Follo )bject Purpose This method is used to connect to the MongoDB using the specified ei This method closes the db and underlying connections close( force, callback) db(dbname, options) It creates a new DB i instance sharing the current socket connections. isConnected(options) The db object It checks if MongoClient is connected. The db object is created for connecting e commonly used methods of db object - Method Purpose addUser(usemame, password, callback) Itadds user to the database. admin() This method retu Admin db instance. Collection(name, options, eallb; yack) ‘etch a specific coll ame we wish to ac error ction. The name isc 3 ‘onction 2¢¢ rhe callback function a a sis anarn} and names parameters where names is! oFcallction names Web Development 3-31 __MONGO DB. (options,callbacks) This met a is method fetche: Xl fetches all the collections for current db. Fcattestions Collection(name, Th coal his met ci | ilback) thod is used to create a new collection on a Server wit i ver with the specified options. | options.c@ ~Collection(name, options, callback Faron Co allback) | It drops the collection from the database, removing. it permanently, of all the collection ‘Collections(filter, options This bs ‘ollections( options) This method is used to get the lis information for the specified db. [—— Fas Pe ola) 1 Explain the MongoDBClient object and the methods associated with it 2, Explain the db object and the methods associated with it. Fil 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 Nodejs 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 andeity. 1) Creation of collection Step 1: We will create a database studentDB. For working directory. I have created the folder by a name StudentDBDenio. h of StudentDBDemo. And issue the that purpose make a folder in your current Step 2: Open the Gommand prompt go ‘ the pat commands. D; \NodeJSExamples\StudentDBDemo>nPm init And press enter key to accept the default values. By this package,json file gets created. using following command Step 3: ‘Then install the mongodb module pm install mongodb D:NodeJSExamples\StudentDBDemo7 PI le for creating e code is as Step 4 : Now create a nodes fi a database and collection. Thi : create a : Follows - Creates Const MongoCtient = require¢mongod) MongoClienti 7 ") Anmedabad” e contents of the collection ified by displaying th The above deletion operation can be verified by disp! Preece ou : Oe ne BO Fy Foo Gaerne 6) Sorting documents ; Data can be arranged in sorted order in the collection. F data we use the method sort. Following code illustrates he order of the filed named city. Sortjs const MongoClient = requuire( mongodb’). MongoClient; const url = "mongodb://127.0.0.1:27017; const client = new MongoClient(url}; 11 Connect to the dabase Const database = "studentsDB", async function getData() { let result = avrait client, : connect); et db = result.db (database) letcotecdon = dy entecns var mydata = {eity:1}; Tet response = await : calection, console, Jog(response); ae —) 8 n(Student_Info'), getData(); se or displaying the sot! ow to display the dam 9S Progran based 0 displayi descend var my lo] 2. ] 3. Fol Eu Fo then t De data j

You might also like