MongoDB – Data Modeling

MongoDB – Data Modelling ”; Previous Next Data in MongoDB has a flexible schema.documents in the same collection. They do not need to have the same set of fields or structure Common fields in a collection’s documents may hold different types of data. Data Model Design MongoDB provides two types of data models: — Embedded data model and Normalized data model. Based on the requirement, you can use either of the models while preparing your document. Embedded Data Model In this model, you can have (embed) all the related data in a single document, it is also known as de-normalized data model. For example, assume we are getting the details of employees in three different documents namely, Personal_details, Contact and, Address, you can embed all the three documents in a single one as shown below − { _id: , Emp_ID: “10025AE336” Personal_details:{ First_Name: “Radhika”, Last_Name: “Sharma”, Date_Of_Birth: “1995-09-26” }, Contact: { e-mail: “[email protected]”, phone: “9848022338” }, Address: { city: “Hyderabad”, Area: “Madapur”, State: “Telangana” } } Normalized Data Model In this model, you can refer the sub documents in the original document, using references. For example, you can re-write the above document in the normalized model as: Employee: { _id: <ObjectId101>, Emp_ID: “10025AE336″ } Personal_details: { _id: <ObjectId102>, empDocID: ” ObjectId101″, First_Name: “Radhika”, Last_Name: “Sharma”, Date_Of_Birth: “1995-09-26″ } Contact: { _id: <ObjectId103>, empDocID: ” ObjectId101″, e-mail: “[email protected]”, phone: “9848022338” } Address: { _id: <ObjectId104>, empDocID: ” ObjectId101″, city: “Hyderabad”, Area: “Madapur”, State: “Telangana” } Considerations while designing Schema in MongoDB Design your schema according to user requirements. Combine objects into one document if you will use them together. Otherwise separate them (but make sure there should not be need of joins). Duplicate the data (but limited) because disk space is cheap as compare to compute time. Do joins while write, not on read. Optimize your schema for most frequent use cases. Do complex aggregation in the schema. Example Suppose a client needs a database design for his blog/website and see the differences between RDBMS and MongoDB schema design. Website has the following requirements. Every post has the unique title, description and url. Every post can have one or more tags. Every post has the name of its publisher and total number of likes. Every post has comments given by users along with their name, message, data-time and likes. On each post, there can be zero or more comments. In RDBMS schema, design for above requirements will have minimum three tables. While in MongoDB schema, design will have one collection post and the following structure − { _id: POST_ID title: TITLE_OF_POST, description: POST_DESCRIPTION, by: POST_BY, url: URL_OF_POST, tags: [TAG1, TAG2, TAG3], likes: TOTAL_LIKES, comments: [ { user:”COMMENT_BY”, message: TEXT, dateCreated: DATE_TIME, like: LIKES }, { user:”COMMENT_BY”, message: TEXT, dateCreated: DATE_TIME, like: LIKES } ] } So while showing the data, in RDBMS you need to join three tables and in MongoDB, data will be shown from one collection only. Print Page Previous Next Advertisements ”;

MongoDB – Data Types

MongoDB – Datatypes ”; Previous Next 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 a numerical value. Integer can be 32 bit or 64 bit depending upon your server. 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 and highest BSON elements. Arrays − This type is used to store arrays or list or multiple values into one key. Timestamp − ctimestamp. This can be handy for recording when a document has been modified or added. Object − This datatype is used for embedded documents. Null − This type is used to store a Null value. Symbol − This datatype is used identically to a string; however, it”s generally reserved for languages that use a specific symbol type. Date − This datatype is used to store the current date or time in UNIX time format. You can specify your own date time by creating object of Date and passing day, month, year into it. Object ID − This datatype is used to store the document’s ID. Binary data − This datatype is used to store binary data. Code − This datatype is used to store JavaScript code into the document. Regular expression − This datatype is used to store regular expression. Print Page Previous Next Advertisements ”;

MongoDB – Advantages

MongoDB – Advantages ”; Previous Next Any relational database has a typical schema design that shows number of tables and the relationship between these tables. While in MongoDB, there is no concept of relationship. Advantages of MongoDB over RDBMS Schema less − MongoDB is a document database in which one collection holds different documents. Number of fields, content and size of the document can differ from one document to another. Structure of a single object is clear. No complex joins. Deep query-ability. MongoDB supports dynamic queries on documents using a document-based query language that”s nearly as powerful as SQL. Tuning. Ease of scale-out − MongoDB is easy to scale. Conversion/mapping of application objects to database objects not needed. Uses internal memory for storing the (windowed) working set, enabling faster access of data. Why Use MongoDB? Document Oriented Storage − Data is stored in the form of JSON style documents. Index on any attribute Replication and high availability Auto-Sharding Rich queries Fast in-place updates Professional support by MongoDB Where to Use MongoDB? Big Data Content Management and Delivery Mobile and Social Infrastructure User Data Management Data Hub Print Page Previous Next Advertisements ”;

MongoDB – Insert Document

MongoDB – Insert Document ”; Previous Next In this chapter, we will learn how to insert document in MongoDB collection. The insert() Method To insert data into MongoDB collection, you need to use MongoDB”s insert() or save() method. Syntax The basic syntax of insert() command is as follows − >db.COLLECTION_NAME.insert(document) Example > db.users.insert({ … _id : ObjectId(“507f191e810c19729de860ea”), … title: “MongoDB Overview”, … description: “MongoDB is no sql database”, … by: “tutorials point”, … url: “http://www.tutorialspoint.com”, … tags: [”mongodb”, ”database”, ”NoSQL”], … likes: 100 … }) WriteResult({ “nInserted” : 1 }) > Here mycol is our collection name, as created in the previous chapter. If the collection doesn”t exist in the database, then MongoDB will create this collection and then insert a document into it. In the inserted document, if we don”t specify the _id parameter, then MongoDB assigns a unique ObjectId for this document. _id is 12 bytes hexadecimal number unique for every document in a collection. 12 bytes are divided as follows − _id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer) You can also pass an array of documents into the insert() method as shown below:. > db.createCollection(“post”) > db.post.insert([ { title: “MongoDB Overview”, description: “MongoDB is no SQL database”, by: “tutorials point”, url: “http://www.tutorialspoint.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: [ { user:”user1″, message: “My first comment”, dateCreated: new Date(2013,11,10,2,35), like: 0 } ] } ]) BulkWriteResult({ “writeErrors” : [ ], “writeConcernErrors” : [ ], “nInserted” : 2, “nUpserted” : 0, “nMatched” : 0, “nModified” : 0, “nRemoved” : 0, “upserted” : [ ] }) > To insert the document you can use db.post.save(document) also. If you don”t specify _id in the document then save() method will work same as insert() method. If you specify _id then it will replace whole data of document containing _id as specified in save() method. 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) Example Following example creates a new collection named empDetails and inserts a document using the insertOne() method. > db.createCollection(“empDetails”) { “ok” : 1 } > db.empDetails.insertOne( { First_Name: “Radhika”, Last_Name: “Sharma”, Date_Of_Birth: “1995-09-26”, e_mail: “[email protected]”, phone: “9848022338” }) { “acknowledged” : true, “insertedId” : ObjectId(“5dd62b4070fb13eec3963bea”) } > The insertMany() method You can insert multiple documents using the insertMany() method. To this method you need to pass an array of documents. Example Following example inserts three different documents into the empDetails collection using the insertMany() method. > db.empDetails.insertMany( [ { First_Name: “Radhika”, Last_Name: “Sharma”, Date_Of_Birth: “1995-09-26”, e_mail: “[email protected]”, phone: “9000012345” }, { First_Name: “Rachel”, Last_Name: “Christopher”, Date_Of_Birth: “1990-02-16”, e_mail: “[email protected]”, phone: “9000054321” }, { First_Name: “Fathima”, Last_Name: “Sheik”, Date_Of_Birth: “1990-02-16”, e_mail: “[email protected]”, phone: “9000054321” } ] ) { “acknowledged” : true, “insertedIds” : [ ObjectId(“5dd631f270fb13eec3963bed”), ObjectId(“5dd631f270fb13eec3963bee”), ObjectId(“5dd631f270fb13eec3963bef”) ] } > Print Page Previous Next Advertisements ”;