MongoDB - Tutorialspoint

3y ago
386 Views
102 Downloads
1.17 MB
23 Pages
Last View : 6d ago
Last Download : 3m ago
Upload by : Elisha Lemon
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 contact@tutorialspoint.comi

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 mongo.exeMongoDB shell version: 2.4.6connecting to: test db.test.save( { a: 1 } ) db.test.find(){ " id" : ObjectId(5879b0f65a56a454), "a" : 1 } This will show that MongoDB is installed and run successfully. Next time when you runMongoDB, you need to issue only commands.D:\set up\mongodb\bin mongod.exe --dbpath "d:\set up\mongodb\data"D:\set up\mongodb\bin mongo.exeInstall MongoDB on UbuntuRun the following command to import the MongoDB public GPG key sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10Create a /etc/apt/sources.list.d/mongodb.list file using the following command.echo 'deb start dist 10gen' sudo tee /etc/apt/sources.list.d/mongodb.listNow issue the following command to update the repository sudo apt-get update10

MongoDBNext install the MongoDB by using the following command apt-get install mongodb-10gen 2.2.3In the above installation, 2.2.3 is currently released MongoDB version. Make sure to installthe latest version always. Now MongoDB is installed successfully.Start MongoDBsudo service mongodb startStop MongoDBsudo service mongodb stopRestart MongoDBsudo service mongodb restartTo use MongoDB run the following command.mongoThis will connect you to running MongoDB instance.MongoDB HelpTo get a list of commands, type db.help() in MongoDB client. This will give you a list ofcommands as shown in the following screenshot.11

MongoDB12

MongoDBMongoDB StatisticsTo get stats about MongoDB server, type the command db.stats() in MongoDB client. Thiswill show the database name, number of collection and documents in the database. Outputof the command is shown in the following screenshot.13

4. MongoDB Data ModellingMongoDBData in MongoDB has a flexible schema.documents in the same collection. They do not needto have the same set of fields or structure, and common fields in a collection’s documentsmay hold different types of data.Some 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 separatethem (but make sure there should not be need of joins). Duplicate the data (but limited) because disk space is cheap as compare to computetime. Do joins while write, not on read. Optimize your schema for most frequent use cases. Do complex aggregation in the schema.ExampleSuppose a client needs a database design for his blog/website and see the differencesbetween 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-timeand likes. On each post, there can be zero or more comments.In RDBMS schema, design for above requirements will have minimum three tables.14

MongoDBWhile in MongoDB schema, design will have one collection post and the following structure:{id: POST IDtitle: 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}]}15

MongoDBSo while showing the data, in RDBMS you need to join three tables and in MongoDB, data willbe shown from one collection only.16

5. MongoDB Create DatabaseMongoDBIn this chapter, we will see how to create a database in MongoDB.The use CommandMongoDB use DATABASE NAME is used to create database. The command will create anew database if it doesn't exist, otherwise it will return the existing database.SyntaxBasic syntax of use DATABASE statement is as follows:use DATABASE NAMEExampleIf you want to create a database with name mydb , then use DATABASE statement wouldbe as follows: use mydbswitched to db mydbTo check your currently selected database, use the command db dbmydbIf you want to check your databases list, use the command show dbs. show dbslocal0.78125GBtest0.23012GBYour created database (mydb) is not present in list. To display database, you need to insertat least one document into it. db.movie.insert({"name":"tutorials point"}) show dbslocal0.78125GBmydb0.23012GB17

MongoDBtest0.23012GBIn MongoDB default database is test. If you didn't create any database, then collections willbe stored in test database.18

6. MongoDB Drop DatabaseMongoDBIn this chapter, we will see how to drop a database using MongoDB command.The dropDatabase() MethodMongoDB db.dropDatabase() command is used to drop a existing database.SyntaxBasic syntax of dropDatabase() command is as follows:db.dropDatabase()This will delete the selected database. If you have not selected any database, then it willdelete default 'test' database.ExampleFirst, check the list of available databases by using the command, show dbs. show dbslocal0.78125GBmydb0.23012GBtest0.23012GB If you want to delete new database mydb , then dropDatabase() command would be asfollows: use mydbswitched to db mydb db.dropDatabase() { "dropped" : "mydb", "ok" : 1 } Now check list of databases. show dbslocal0.78125GBtest0.23012GB 19

7. MongoDB Create CollectionMongoDBIn this chapter, we will see how to create a collection using MongoDB.The createCollection() MethodMongoDB db.createCollection(name, options) is used to create collection.SyntaxBasic syntax of createCollection() command is as follows:db.createCollection(name, options)In the command, name is name of collection to be created. Options is a document and isused to specify configuration of escriptionName of the collection to be created(Optional) Specify options about memorysize and indexingOptions parameter is optional, so you need to specify only the name of the collection.Following is the list of options you can use:Fi

MongoDB 5 MongoDB is a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on concept of collection and document.

Related Documents:

yum install mongodb mongodb-server (from EPEL). Ubuntu/Debian: apt-get install mongodb (from universe). Mac OS X (with Homebrew): brew install mongodb To configure: edit/etc/mongod.conf. 2.6, 2.4 and older: old key–value format. 2.6 and newer: new YAML format Start the MongoDB servic

Installing the MongoDB depends on the operating system on which you are installing it. See the MongoDB documentation for details on how to install MongoDB in your environment. This guide used a RedHat Linux 8 installation. Follow the installation steps in the Install MongoDB Enterprise Edition on Red Hat or CentOS guide from the mongoDB .

Why NoSQL? 195 Understanding MongoDB 196 MongoDB Data Types 197. Contents ix Planning Your Data Model 199 Summary 205 Up Next 205 12 Getting Started with MongoDB 207 Building the MongoDB Environment 207 Adminis

For non-relational databases, we used the MongoDB C# Driver that is the officially supported C# driver for MongoDB. The version of the driver is 2.0 and the version of MongoDB is 3.0. To be able to connect to MongoDB we used a MongoClient. In code, we used two namespaces that are specific to MongoDB: M

MongoDB is a general-purpose document store. MongoDB is intended to store "schema-less" data, in which each object may have a different structure. In practice, MongoDB is typically used to store large, variable-sized payloads represented as JSON or BSON objects. Both because of MongoDB's generality, and because of its design as a schema-less .

TP MongoDB Ce TP a pour objectif de vous familiariser avec MongoDB et son shell. Vous allez dans la suite charger un jeu de données et écrire les requêtes permettant chacune de répondre à un besoin en information précis. Introduction MongoDB est une base de données NoSQL orientée documents. Une base de données MongoDB

MongoDB MongoDB Notes for Professionals Notes for Professionals GoalKicker.com Free Programming Books Disclaimer This is an uno cial free book created for educational purposes and is not a liated with o cial MongoDB group(s) or company(s). All trademarks and registered trademarks are the property of their respective owners 60 pagesFile Size: 931KBPage Count: 73

The Question is, “Am I my brother’s keeper?” Am I My Brother’s Keeper, Bill Scheidler 4 Deuteronomy 25:5-10 – God challenges brothers to build up the house of their brothers. “If brothers dwell together, and one of them dies and has no son, the widow of the dead man shall not be married to a stranger outside the family; her husband’s brother shall go in to her, take her as his .