Transcription

MongoDBAbout the TutorialMongoDB is an open-source document database and leading NoSQL database. MongoDBis written in C .This tutorial will give you great understanding on MongoDB concepts needed to create anddeploy a highly scalable and performance-oriented database.AudienceThis tutorial is designed for Software Professionals who are willing to learn MongoDBDatabase in simple and easy steps. It will throw light on MongoDB concepts and aftercompleting this tutorial you will be at an intermediate level of expertise, from where youcan take yourself at higher level of expertise.PrerequisitesBefore proceeding with this tutorial, you should have a basic understanding of database,text editor and execution of programs, etc. Because we are going to develop highperformance database, so it will be good if you have an understanding on the basicconcepts of Database (RDBMS).Copyright & Disclaimer Copyright 2018 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I)Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republishany contents or a part of contents of this e-book in any manner without written consentof the publisher.We strive to update the contents of our website and tutorials as timely and as precisely aspossible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of ourwebsite or its contents including this tutorial. If you discover any errors on our website orin this tutorial, please notify us at [email protected]

MongoDBTable of ContentsAbout the Tutorial . iAudience . iPrerequisites . iCopyright & Disclaimer . iTable of Contents. iiMONGODB. 11.MongoDB Overview . 22.MongoDB Advantages . 43.MongoDB Environment . 54.MongoDB Data Modelling . 105.MongoDB Create Database . 126.MongoDB Drop Database . 137.MongoDB Create Collection . 148.MongoDB Drop Collection . 169.MongoDB Datatypes . 1710. MongoDB Insert Document . 1811. MongoDB Query Document . 2012. MongoDB Update Document . 2413. MongoDB Delete Document . 2614. MongoDB Projection . 2815. MongoDB Limit Records . 2916. MongoDB Sort Records . 3117. MongoDB Indexing . 3218. MongoDB Aggregation . 3419. MongoDB Replication . 3820. MongoDB Sharding. 4121. MongoDB Create Backup . 43ii

MongoDB22. MongoDB Deployment . 4523. MongoDB Java. 4824. MongoDB PHP . 60ADVANCED MONGODB . 6625. MongoDB Relationships . 6726. MongoDB Database References . 7027. MongoDB Covered Queries . 7228. MongoDB Analyzing Queries . 7429. MongoDB Atomic Operations . 7630. MongoDB Advanced Indexing . 7831. MongoDB Indexing Limitations . 8032. MongoDB ObjectId . 8133. MongoDB MapReduce. 8334. MongoDB Text Search . 8635. MongoDB Regular Expression . 8836. MongoDB RockMongo. 9037. MongoDB GridFS . 9138. MongoDB Capped Collections . 9339. MongoDB Auto-Increment Sequence . 95iii

MongoDBMongoDB4

1. MongoDB OverviewMongoDBMongoDB is a cross-platform, document oriented database that provides, high performance,high availability, and easy scalability. MongoDB works on concept of collection and document.DatabaseDatabase is a physical container for collections. Each database gets its own set of files on thefile system. A single MongoDB server typically has multiple databases.CollectionCollection is a group of MongoDB documents. It is the equivalent of an RDBMS table. Acollection exists within a single database. Collections do not enforce a schema. Documentswithin a collection can have different fields. Typically, all documents in a collection are ofsimilar or related purpose.DocumentA document is a set of key-value pairs. Documents have dynamic schema. Dynamic schemameans that documents in the same collection do not need to have the same set of fields orstructure, and common fields in a collection's documents may hold different types of data.The following table shows the relationship of RDBMS terminology with nTuple/RowDocumentcolumnFieldTable JoinEmbedded DocumentsPrimary KeyPrimary Key (Default key id provided bymongodb itself)Database Server and ClientMysqld/Oraclemongod5

MongoDBmysql/sqlplusmongoSample DocumentFollowing example shows the document structure of a blog site, which is simply a commaseparated key value pair.{id: ObjectId(7df78ad8902c)title: 'MongoDB Overview',description: 'MongoDB is no sql database',by: 'tutorials point',url: 'http://www.tutorialspoint.com',tags: ['mongodb', 'database', 'NoSQL'],likes: 100,comments: [{user:'user1',message: 'My first comment',dateCreated: new Date(2011,1,20,2,15),like: 0},{user:'user2',message: 'My second comments',dateCreated: new Date(2011,1,25,7,45),like: 5}]}id is a 12 bytes hexadecimal number which assures the uniqueness of every document. Youcan provide id while inserting the document. If you don’t provide then MongoDB provides aunique id for every document. These 12 bytes first 4 bytes for the current timestamp, next 3bytes for machine id, next 2 bytes for process id of MongoDB server and remaining 3 bytesare simple incremental VALUE.6

2. MongoDB AdvantagesMongoDBAny relational database has a typical schema design that shows number of tables and therelationship 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 differentdocuments. Number of fields, content and size of the document can differ from onedocument to another. Structure of a single object is clear. No complex joins. Deep query-ability. MongoDB supports dynamic queries on documents using adocument-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 accessof 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 MongoDBWhere to Use MongoDB? Big Data Content Management and Delivery Mobile and Social Infrastructure7

MongoDB User Data Management Data Hub8

3. MongoDB EnvironmentMongoDBLet us now see how to install MongoDB on Windows.Install MongoDB on WindowsTo install MongoDB on Windows, first download the latest release of MongoDBfrom http://www.mongodb.org/downloads. Make sure you get correct version of MongoDBdepending upon your Windows version. To get your Windows version, open command promptand execute the following command.C:\ wmic os get osarchitectureOSArchitecture64-bitC:\ 32-bit versions of MongoDB only support databases smaller than 2GB and suitable only fortesting and evaluation purposes.Now extract your downloaded file to c:\ drive or any other location. Make sure the name ofthe extracted folder is mongodb-win32-i386-[version] or mongodb-win32-x86 64-[version].Here [version] is the version of MongoDB download.Next, open the command prompt and run the following command.C:\ move mongodb-win64-* mongodb1 dir(s) moved.C:\ In case you have extracted the MongoDB at different location, then go to that path by usingcommand cd FOOLDER/DIR and now run the above given process.MongoDB requires a data folder to store its files. The default location for the MongoDB datadirectory is c:\data\db. So you need to create this folder using the Command Prompt. Executethe following command sequence.C:\ md dataC:\md data\dbIf you have to install the MongoDB at a different location, then you need to specify an alternatepath for \data\db by setting the path dbpath in mongod.exe. For the same, issue thefollowing commands.9

MongoDBIn the command prompt, navigate to the bin directory present in the MongoDB installationfolder. Suppose my installation folder is D:\set up\mongodbC:\Users\XYZ d:D:\ cd "set up"D:\set up cd mongodbD:\set up\mongodb cd binD:\set up\mongodb\bin mongod.exe --dbpath "d:\set up\mongodb\data"This will show waiting for connections message on the console output, which indicates thatthe mongod.exe process is running successfully.Now to run the MongoDB, you need to open another command prompt and issue the followingcommand.D:\set up\mongodb\bin mong