MongoDB – PHP

MongoDB – PHP ”; Previous Next To use MongoDB with PHP, you need to use MongoDB PHP driver. Download the driver from the url Download PHP Driver. Make sure to download the latest release of it. Now unzip the archive and put php_mongo.dll in your PHP extension directory (“ext” by default) and add the following line to your php.ini file − extension = php_mongo.dll Make a Connection and Select a Database To make a connection, you need to specify the database name, if the database doesn”t exist then MongoDB creates it automatically. Following is the code snippet to connect to the database − <?php // connect to mongodb $m = new MongoClient(); echo “Connection to database successfully”; // select a database $db = $m->mydb; echo “Database mydb selected”; ?> When the program is executed, it will produce the following result − Connection to database successfully Database mydb selected Create a Collection Following is the code snippet to create a collection − <?php // connect to mongodb $m = new MongoClient(); echo “Connection to database successfully”; // select a database $db = $m->mydb; echo “Database mydb selected”; $collection = $db->createCollection(“mycol”); echo “Collection created succsessfully”; ?> When the program is executed, it will produce the following result − Connection to database successfully Database mydb selected Collection created succsessfully Insert a Document To insert a document into MongoDB, insert() method is used. Following is the code snippet to insert a document − <?php // connect to mongodb $m = new MongoClient(); echo “Connection to database successfully”; // select a database $db = $m->mydb; echo “Database mydb selected”; $collection = $db->mycol; echo “Collection selected succsessfully”; $document = array( “title” => “MongoDB”, “description” => “database”, “likes” => 100, “url” => “http://www.tutorialspoint.com/mongodb/”, “by” => “tutorials point” ); $collection->insert($document); echo “Document inserted successfully”; ?> When the program is executed, it will produce the following result − Connection to database successfully Database mydb selected Collection selected succsessfully Document inserted successfully Find All Documents To select all documents from the collection, find() method is used. Following is the code snippet to select all documents − <?php // connect to mongodb $m = new MongoClient(); echo “Connection to database successfully”; // select a database $db = $m->mydb; echo “Database mydb selected”; $collection = $db->mycol; echo “Collection selected succsessfully”; $cursor = $collection->find(); // iterate cursor to display title of documents foreach ($cursor as $document) { echo $document[“title”] . “n”; } ?> When the program is executed, it will produce the following result − Connection to database successfully Database mydb selected Collection selected succsessfully { “title”: “MongoDB” } Update a Document To update a document, you need to use the update() method. In the following example, we will update the title of inserted document to MongoDB Tutorial. Following is the code snippet to update a document − <?php // connect to mongodb $m = new MongoClient(); echo “Connection to database successfully”; // select a database $db = $m->mydb; echo “Database mydb selected”; $collection = $db->mycol; echo “Collection selected succsessfully”; // now update the document $collection->update(array(“title”=>”MongoDB”), array(”$set”=>array(“title”=>”MongoDB Tutorial”))); echo “Document updated successfully”; // now display the updated document $cursor = $collection->find(); // iterate cursor to display title of documents echo “Updated document”; foreach ($cursor as $document) { echo $document[“title”] . “n”; } ?> When the program is executed, it will produce the following result − Connection to database successfully Database mydb selected Collection selected succsessfully Document updated successfully Updated document { “title”: “MongoDB Tutorial” } Delete a Document To delete a document, you need to use remove() method. In the following example, we will remove the documents that has the title MongoDB Tutorial. Following is the code snippet to delete a document − <?php // connect to mongodb $m = new MongoClient(); echo “Connection to database successfully”; // select a database $db = $m->mydb; echo “Database mydb selected”; $collection = $db->mycol; echo “Collection selected succsessfully”; // now remove the document $collection->remove(array(“title”=>”MongoDB Tutorial”),false); echo “Documents deleted successfully”; // now display the available documents $cursor = $collection->find(); // iterate cursor to display title of documents echo “Updated document”; foreach ($cursor as $document) { echo $document[“title”] . “n”; } ?> When the program is executed, it will produce the following result − Connection to database successfully Database mydb selected Collection selected successfully Documents deleted successfully In the above example, the second parameter is boolean type and used for justOne field of remove() method. Remaining MongoDB methods findOne(), save(), limit(), skip(), sort() etc. works same as explained above. Print Page Previous Next Advertisements ”;

MongoDB – Questions and Answers

MongoDB Questions and Answers ”; Previous Next MongoDB Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations. SN Question/Answers Type 1 MongoDB Interview Questions This section provides a huge collection of MongoDB Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer. 2 MongoDB Online Quiz This section provides a great collection of MongoDB Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation. If you select the right option, it turns green; else red. 3 MongoDB Online Test If you are preparing to appear for a Java and MongoDB Framework related certification exam, then this section is a must for you. This section simulates a real online test along with a given timer which challenges you to complete the test within a given time-frame. Finally you can check your overall test score and how you fared among millions of other candidates who attended this online test. 4 MongoDB Mock Test This section provides various mock tests that you can download at your local machine and solve offline. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Print Page Previous Next Advertisements ”;

MongoDB – Capped Collections

MongoDB – Capped Collections ”; Previous Next Capped collections are fixed-size circular collections that follow the insertion order to support high performance for create, read, and delete operations. By circular, it means that when the fixed size allocated to the collection is exhausted, it will start deleting the oldest document in the collection without providing any explicit commands. Capped collections restrict updates to the documents if the update results in increased document size. Since capped collections store documents in the order of the disk storage, it ensures that the document size does not increase the size allocated on the disk. Capped collections are best for storing log information, cache data, or any other high volume data. Creating Capped Collection To create a capped collection, we use the normal createCollection command but with capped option as true and specifying the maximum size of collection in bytes. >db.createCollection(“cappedLogCollection”,{capped:true,size:10000}) In addition to collection size, we can also limit the number of documents in the collection using the max parameter − >db.createCollection(“cappedLogCollection”,{capped:true,size:10000,max:1000}) If you want to check whether a collection is capped or not, use the following isCapped command − >db.cappedLogCollection.isCapped() If there is an existing collection which you are planning to convert to capped, you can do it with the following code − >db.runCommand({“convertToCapped”:”posts”,size:10000}) This code would convert our existing collection posts to a capped collection. Querying Capped Collection By default, a find query on a capped collection will display results in insertion order. But if you want the documents to be retrieved in reverse order, use the sort command as shown in the following code − >db.cappedLogCollection.find().sort({$natural:-1}) There are few other important points regarding capped collections worth knowing − We cannot delete documents from a capped collection. There are no default indexes present in a capped collection, not even on _id field. While inserting a new document, MongoDB does not have to actually look for a place to accommodate new document on the disk. It can blindly insert the new document at the tail of the collection. This makes insert operations in capped collections very fast. Similarly, while reading documents MongoDB returns the documents in the same order as present on disk. This makes the read operation very fast. 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 ”;

MongoDB – Create Database

MongoDB – Create Database ”; Previous Next In this chapter, we will see how to create a database in MongoDB. The use Command MongoDB use DATABASE_NAME is used to create database. The command will create a new database if it doesn”t exist, otherwise it will return the existing database. Syntax Basic syntax of use DATABASE statement is as follows − use DATABASE_NAME Example If you want to use a database with name <mydb>, then use DATABASE statement would be as follows − >use mydb switched to db mydb To check your currently selected database, use the command db >db mydb If you want to check your databases list, use the command show dbs. >show dbs local 0.78125GB test 0.23012GB Your created database (mydb) is not present in list. To display database, you need to insert at least one document into it. >db.movie.insert({“name”:”tutorials point”}) >show dbs local 0.78125GB mydb 0.23012GB test 0.23012GB In MongoDB default database is test. If you didn”t create any database, then collections will be stored in test database. Print Page Previous Next Advertisements ”;

MongoDB – Environment

MongoDB – Environment ”; Previous Next Let us now see how to install MongoDB on Windows. Install MongoDB On Windows To install MongoDB on Windows, first download the latest release of MongoDB from https://www.mongodb.com/download-center. Enter the required details, select the Server tab, in it you can choose the version of MongoDB, operating system and, packaging as: Now install the downloaded file, by default, it will be installed in the folder C:Program Files. MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is c:datadb. So you need to create this folder using the Command Prompt. Execute the following command sequence. C:>md data C:md datadb Then you need to specify set the dbpath to the created directory in mongod.exe. For the same, issue the following commands. In the command prompt, navigate to the bin directory current in the MongoDB installation folder. Suppose my installation folder is C:Program FilesMongoDB C:UsersXYZ>d:cd C:Program FilesMongoDBServer4.2bin C:Program FilesMongoDBServer4.2bin>mongod.exe –dbpath “C:data” This will show waiting for connections message on the console output, which indicates that the mongod.exe process is running successfully. Now to run the MongoDB, you need to open another command prompt and issue the following command. C:Program FilesMongoDBServer4.2bin>mongo.exe MongoDB shell version v4.2.1 connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { “id” : UUID(“4260beda-f662-4cbe-9bc7-5c1f2242663c”) } MongoDB server version: 4.2.1 > This will show that MongoDB is installed and run successfully. Next time when you run MongoDB, you need to issue only commands. C:Program FilesMongoDBServer4.2bin>mongod.exe –dbpath “C:data” C:Program FilesMongoDBServer4.2bin>mongo.exe Install MongoDB on Ubuntu Run the following command to import the MongoDB public GPG key − sudo apt-key adv –keyserver hkp://keyserver.ubuntu.com:80 –recv 7F0CEB10 Create a /etc/apt/sources.list.d/mongodb.list file using the following command. echo ”deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen” | sudo tee /etc/apt/sources.list.d/mongodb.list Now issue the following command to update the repository − sudo apt-get update Next install the MongoDB by using the following command − apt-get install mongodb-10gen = 4.2 In the above installation, 2.2.3 is currently released MongoDB version. Make sure to install the latest version always. Now MongoDB is installed successfully. Start MongoDB sudo service mongodb start Stop MongoDB sudo service mongodb stop Restart MongoDB sudo service mongodb restart To use MongoDB run the following command. mongo This will connect you to running MongoDB instance. MongoDB Help To get a list of commands, type db.help() in MongoDB client. This will give you a list of commands as shown in the following screenshot. MongoDB Statistics To get stats about MongoDB server, type the command db.stats() in MongoDB client. This will show the database name, number of collection and documents in the database. Output of the command is shown in the following screenshot. Print Page Previous Next Advertisements ”;

MongoDB – Overview

MongoDB – Overview ”; Previous Next 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. Database Database is a physical container for collections. Each database gets its own set of files on the file system. A single MongoDB server typically has multiple databases. Collection Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection are of similar or related purpose. Document A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection”s documents may hold different types of data. The following table shows the relationship of RDBMS terminology with MongoDB. RDBMS MongoDB Database Database Table Collection Tuple/Row Document column Field Table Join Embedded Documents Primary Key Primary Key (Default key _id provided by MongoDB itself) Database Server and Client mysqld/Oracle mongod mysql/sqlplus mongo Sample Document Following example shows the document structure of a blog site, which is simply a comma separated 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. You can provide _id while inserting the document. If you don’t provide then MongoDB provides a unique id for every document. These 12 bytes first 4 bytes for the current timestamp, next 3 bytes for machine id, next 2 bytes for process id of MongoDB server and remaining 3 bytes are simple incremental VALUE. Print Page Previous Next Advertisements ”;

MongoDB – Drop Database

MongoDB – Drop Database ”; Previous Next In this chapter, we will see how to drop a database using MongoDB command. The dropDatabase() Method MongoDB db.dropDatabase() command is used to drop a existing database. Syntax Basic syntax of dropDatabase() command is as follows − db.dropDatabase() This will delete the selected database. If you have not selected any database, then it will delete default ”test” database. Example First, check the list of available databases by using the command, show dbs. >show dbs local 0.78125GB mydb 0.23012GB test 0.23012GB > If you want to delete new database <mydb>, then dropDatabase() command would be as follows − >use mydb switched to db mydb >db.dropDatabase() >{ “dropped” : “mydb”, “ok” : 1 } > Now check list of databases. >show dbs local 0.78125GB test 0.23012GB > Print Page Previous Next Advertisements ”;

MongoDB – Create Collection

MongoDB – Create Collection ”; Previous Next In this chapter, we will see how to create a collection using MongoDB. The createCollection() Method MongoDB db.createCollection(name, options) is used to create collection. Syntax Basic 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 is used to specify configuration of collection. Parameter Type Description Name String Name of the collection to be created Options Document (Optional) Specify options about memory size and indexing Options parameter is optional, so you need to specify only the name of the collection. Following is the list of options you can use − Field Type Description capped Boolean (Optional) If true, enables a capped collection. Capped collection is a fixed size collection that automatically overwrites its oldest entries when it reaches its maximum size. If you specify true, you need to specify size parameter also. autoIndexId Boolean (Optional) If true, 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 need to specify this field also. max number (Optional) Specifies the maximum number of documents allowed in the capped collection. While inserting the document, MongoDB first checks size field of capped collection, then it checks max field. Examples Basic syntax of createCollection() method without options is as follows − >use test switched to db test >db.createCollection(“mycollection”) { “ok” : 1 } > You can check the created collection by using the command show collections. >show collections mycollection system.indexes The following example shows the syntax of createCollection() method with few important options − > db.createCollection(“mycol”, { capped : true, autoIndexID : true, size : 6142800, max : 10000 } ){ “ok” : 0, “errmsg” : “BSON field ”create.autoIndexID” is an unknown field.”, “code” : 40415, “codeName” : “Location40415″ } > In MongoDB, you don”t need to create collection. MongoDB creates collection automatically, when you insert some document. >db.tutorialspoint.insert({“name” : “tutorialspoint”}), WriteResult({ “nInserted” : 1 }) >show collections mycol mycollection system.indexes tutorialspoint > Print Page Previous Next Advertisements ”;