You are on page 1of 15
UNIT-4 Curd Operation 4.1 Create Database MongoDB use DATABASE_NAME is used to create database. The command will ereate a new database if it doesnt exis, otherwise it will retum the existing database. Syntax Basie syntax of use DATABASE statement is as follows — use DATABASE_NAME If you want to use a database with name , then use Di follows — >use mydb switched to db mydb If you want to check your databases list, use the command show dbs. “ show dbs ‘The dropDatabase() Meth Atti will dette the selected database: Ifyou have nt selected any database, then it will delete default ‘test database. Exam} First, check ge list oRAvailable databases by using the command, show dbs. >show dbs local 0.781256B mydb 0.23012GB test 0,23012GB If you want to delete new database , then dropDatabase() command would be as follows ~ >use mydb switched to db mydb >db.dropDatabase() >{ “dropped” : "mydb", "ok" 1} 43 Create collection ‘The ereateCollection() Method MongoDB db.createCollection(name, options) is used to create cg ‘Syntax Basic syntax of ereateCollection() command is as follo db.createCollection(name, options) locur In the command, name is name of collection ta, be 1 fd is used 10 specify configuration of collection, Type Description Ril Ring giyA collection tobe created Options cuMygt Optional) Specify options about memory size and indexing Field Type Description (Optional) If true, enables a capped collection. Capped collection is a fixed size collection that automatically overwrites its oldest centres when it reaches its maximum size. If you specify true, you need to specify size parameter also. autoindexld Boolean (Optional) If truc, automatically create index on _id field.s Default value is false. size number (Optional) Specifies a maximum size in bytes for a capped collection. If capped is true, then you nee ify this ield also. max number (Optional) Specifies the maximum y MG ation in the capped collection, While inserting the document, MongoDB first checks it checks max field, Examples Basic syntax of ereateCollection() method >use test switched to db test db,createCollection("myes Yok" 50, errmsg” *eode" : 4041 *eodeName" = } > In MongoDB, you don't need to create collection, MongoDB creates collection automatically, when you insert some document. >db.tutorialspoint.insert({"name" : “tutorialspoint"}), ‘WriteResult({ “nlnserted" : 1 }) show collections mycol mycollection system. indexes tutotialspoint 44 Drop Collection ‘The drop() Method MongoDB's db.collection.drop( is used to drop a collection from y@Mfatabas ‘Syntax Basic syntax of drop( command is ¢s follows ~ db,COLLECTION_NAME.crop() Example First, check the available collections into yoy em use mydb switched to db mya >show collections mycol mycollection system. indexes tutorialspoint ‘Now drop the col tutorialspoint 4.5 Data Types in MONGODB MongoDB supports many datatypes, Some of them are~ ‘© String — This is the most commonly used datatype to store the data, String in MongoDB. ‘must be UTF-8 valid. © Integer This type is used to store depending upon your server. ‘numerical value, Integer can be 32 bit or 64 bit ‘© Boolean ~ this type is used to store a Boolean (true/false) value. ‘© Double — this type is used to store floating point values. © Min/ Max keys ~ this type is used to compare a value against the lowest gudheaighest BSON. clemnents ‘© Arrays ~ this type is used to store arrays or list or multiple values inf © Timestamp ~ timestamp. This can be handy for recording doc modified or added © Object ~ This data type is used for embedded document ‘© Null ~ This type is used to store a Null value 4.6 Insert Document ‘The insert () Method To insert data into MongoDB collectign, yafgpocd to us at ‘or save() method, Syntax ‘The basic syntax of insert() gommand is MAIO >db.COLLECTION_NAME.im Example ‘The insertOne() method If you need to insert only one document into a collection you can use this method, ‘Syntax ‘The basic syntax of insert() command is as follows ~ >db.COLLECTION_NAME..insertOne(document) UNIT-4 Curd Operation Example Following example creates a new collection named empDetails and inserts a document using the insertOneQ) method. > db.createCollection("empDetails") {ok" 1} > db.empDetails.insetOne( { First_Name: "Radhika", Last_Name: "Sharma’, Date_Of Birth: "1995-09-26", mail: “radhike_sharma.123@ gmail.com’, phone: "9848022338" » t “acknowledged” : true, “insertedld” : Objectld("Sdd624070f 3ece: } > ‘The insertMany() method (Many() mild. To this method you need to pass ‘You can insert multiple document an array of documents. Example Following examply ts into the empDetails collection using the insert Many() m > db.empDgails.i ye: "Radhika", e: "Sharma", Date_Of Birth: "1995-09-26", ,_mail: "radhika_sharma.123@ gmail.com’, ‘phone: "9000012345" First_Name: "Rachel", Last_Name: "Christopher", Date_Of Birth: "1990-02-16", email: "Rachel_Christopher.123@gmail.com", phone: "9000054321" First_Name: "Fathima", Last_Name: "Sheik", Date_Of Birth: "1990-02-16", UNIT-4 Curd Operation ¢_mail: "Fathima_Sheik.123@gmail.com", phone: "9000054321" “acknowledged” : true, "insertedlds" :[ Objectld ("'5dd63112701b13eec3963bed"), Objectld("5dd6311270f 13cee3963bec"), Objectld("5dd631127013eee3963bef") 4.7 Mongo DB Query Document Using Find () Methd ‘The find() Method ‘To query data from MongoDB collection, yflu need to uss Syntax ‘The basic syntax of find () method is a db, COLLECTION_NAl find() method will display all th structured way. ow it using the insert() method as shown below — title: "MongoDB Overview", description: "MongoDB is no SQL database", by: "tutorials point", url: “http:/wwwctutorialspoint.com", tags: ("mongodb”, “database”, "NoSQL"), likes: 100 title: "NoSQL Database", description: "NoSQL database doesn't have tables", by: "tutorials point", url: “http:/www.tutorialspoint.com’ tags: ["mongodb", "database", "NoSQL"), likes: 20, comments: [ f user"userl", ‘message: "My first comment", dateCreated: new Date(2013,11,10.2,35), like: 0 } ] D > db.mycol find) {"" id" : Objectld("Sdd4e2ec082143b44607 ‘"MongoDB is no SQL database", "by" : "tu igs": ["mongodb, "databas jew"! "description" torialspoint.com", "NoSQL" J, "likes" : 20, , "dateCreated" use pretty() method. "jd" : Objectld("Sdd4e2ec0821d3b44607534e"), ile” : "MongoDB Overview", “description” : "MongoDB is no SQL database", “by" : "tutorials point’, “url”: “https wwo.tutorialspoint.com", sags": [ "mongodb", "database", UNIT-4 Curd Operation "NosQL” Ik “likes” : 100 “jd” : Objectld("Sdd4e2ec0821d3b44607534d"), “fitle" :"NoSQL Database", "description" : "NoSQL database doesn't have tables", "by" : "tutorials point", “url” :"http:/www.tutorialspoint.com’", “tags” “mongodb "database", "NoSQL” 1 tikes" : 20, “comments” :[ t "message" : } ‘The findOned methog Apart from the fig I, that returns only one document, incnt with title MongoDB Overview. \g0DB Overview"}) tutorials point”, tp://wwrw.tutorialspoint.com’, “mongodb", "database", "NoSQL" 1 “likes” : 100 MongoDB's update() and save() methods are used to update document into a collection. The ‘update() method updates the values in the existing document while the save() laces the cxisting document with the document passed in save() method. MongoDB Update() Method ‘The updated) method updates the values in the existing document. Syntax ‘The basic syntax of update() method is as follows ~ > db. COLLECTION_NAME..update(SELECTION_CRI Example Consider the mycol collection has the follow {id : Objecttd(598354878133 ladF4Sec: {Lid : Objecttd(598354878133 1adig5ect {Lid : Objectld(5983548781331, >db.mycol.update( WriteResult({ "a >db.mycol.find), "New MongoDB Tutorial” } "NoSQL Overview"} "Tutorials Point Overview"} ‘The save() method replaces the exis method. document with the new document passed in the save() Syntax ‘The basic syntax of MongoDB save() method is shown below — db. COLLECTION_NAME.save({_id:Objectld(). NEW_DATA}) Example Following example will replace the document with the _id ‘598354878133 ladf4SecS’ >db.mycol save( t id” : Objectld("S07191e810c19729de860ea"), “title":" Tutorials Point New Topic", "py":"Tutorials Point” } ) ‘WriteResult({ “nMatched" : 0, ‘nlipserted” : 1, “nModified" : 0, “id” : Objectld("507f191e810c19729de860eq v >db.mycol find() ("ia : Objectld("S07£19 1e810c19729de860, “by":"Tutorials Point") Objecttac” lection named empDetails and inserted three documents in it as shown > db.empDetail ygértMany( C { First_Name: "Radhika", Last_Name: "Sharma’, Ages"26", ¢_mail: "radbika_sharma.123@gmail.com’, phone: "9000012345" h UNIT-4 Curd Operation First_Name: "Rachel", Last_Name: "Christopher", ‘Age "27 € mail; "Rachel_Christopher.123@gmail.com", phone: "9000084321" First_Name: "Fathima, Last_Name: "Sheik", Age: "24", € mail: "Fathima_Sheik. 123@gmail.c hone: "9000054321" ) > db.empDetails findOneAndUpdate( ‘{First_Name:'Radhika'}, " id” : Objectld("5dd66568; rt_Name" : "Radhika", ‘which matches the given filter. ‘method is as follows ~ supdateOne() > db.empDetailsAipdateOne( {First_Name: 'Radhika'}, { Sseti {Age:'30'¢_mail: ‘radhika_newemail@gmail.com'}}, ) { "acknowledged! : true, "matchedCount”: 1, "modifiedCount" : 0 } MongoDB updateMany() method Te updateMany() method updates all the documents that matches the given filter. Syntax ‘The basic syntax of updateMany() method is as follows db, COLLECTION_NAME.update(=titer>, ) Example > db.empDetails.updateMany( {Age:{ Set: "25" }}, 4 Sset: { Age: '00"}} ) { "acknowledged" : true, "matchedCount" : 2, "modified You can see the updated values if you retrieve the cont method as shown below > db.empDetals.find() {ia : Objectld("Sdd6636870 13ecc39 “Sharma”, "Age" :"00", "e_mail” :" {" id” : Objecttd(*5dd66368701bi4 "Christopher", "Age" :"00", "e_mail” 9900054321" } ("id : Objectta("sddes Age”: "24", Ye mal a Fathima’, "Last_Name” : "Sheik" com", "phone" : "9000054321" } GE 0 remove a document from the collection. remove() method 1 is deletion criteria and second is justOne flag. Basic syntax of remove() method is as follows — >db, COLLECTION_NAME.remove(DELLETION_CRITTERIA) Example Consider the mycol collection has the following data, {Lid : Objectid("S07£191e810c19729de860e1"), ttle: "MongoDB Overview"), {Cid : Objectld("S074191e810c19729de860e2"), ttle: "NoSQL Overview"), {_id : ObjectlA("S07119 1e810c19729de860e3"), ttle: "Tutorials Point Overview") Following example will remove all the documents whose ttle is MongoDB Overview’. >db.mycol.remove( tile’ MongoDB Overview'}) ‘WriteResult({"uRemoved" : 1}) > db.mycol.find() {*_id" : Objectld("s071191e810c19729de860e2"), “ttle” : "NoSQL. Overview" {°Lid" : Objectld("5071191e810c19729de860e3"), “title” : "Tutorials Point O yl Remove Only One If there are multiple records and you want to delete only the first om in remove) method. >db.COLLECTION_NAME.remove(DELETION_CRITER Remove All Documents If you don't specify deletion criteria, then hg Je dogpRents from the collection. This is equivalent of SQL's tr > db.mycol.remove({}) WriteResult({ "nRemoved" : 2 }) > db.mycol.find() 4.11 Mongo DB Pra only the necessary data rather than selecting whole of the id you need to show only 3, then select only 3 fields a AM inMongoDB Query Document accepts second optional ‘of fields that you want to retrieve, In MongoDB, when you isplays all fields of a document. To limit this, you need to set a list of. ised to show the field while 0 is used to hide the fields. >db, COLLECTION_NAME find (},{KEV:1}) Example Consider the collection myeo! has the following data ~ {id : Objectld("5071191€810c19729de860eI"), ttle: "MongoDB Overview"), {Cid : Objectld("507M191e810c19729de860e2"), ttle: "NoSQL Overview}, {Cid : Objectld('507M191e810c19729de860e3"), ttle: "Tutorials Point Overview") UNIT-4 Curd Operation Following cxample will display the title of the document while querying the document. >db.mycol.find( {},{"title":1,_id:0}) {title":" MongoDB Overview") {htitle":"NoSQL Overview") {"title":" Tutorials Point Overview") >

You might also like