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 ”;
Category: mongodb
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 – 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 ”;
MongoDB – Drop Collection
MongoDB – Drop Collection ”; Previous Next In this chapter, we will see how to drop a collection using MongoDB. The drop() Method MongoDB”s db.collection.drop() is used to drop a collection from the database. Syntax Basic syntax of drop() command is as follows − db.COLLECTION_NAME.drop() Example First, check the available collections into your database mydb. >use mydb switched to db mydb >show collections mycol mycollection system.indexes tutorialspoint > Now drop the collection with the name mycollection. >db.mycollection.drop() true > Again check the list of collections into database. >show collections mycol system.indexes tutorialspoint > drop() method will return true, if the selected collection is dropped successfully, otherwise it will return false. Print Page Previous Next Advertisements ”;
MongoDB – Home
MongoDB Tutorial Table of content MongoDB Tutorial Why to Learn MongoDB? MongoDB Applications Who Should Learn MongoDB Prerequisites to Learn MongoDB MongoDB Jobs and Opportunities Frequently Asked Questions about MongoDB PDF Version Quick Guide Resources Job Search Discussion MongoDB Tutorial The MongoDB is an open-source document database and leading NoSQL database. MongoDB is written in C++. This tutorial will give you great understanding on MongoDB concepts needed to create and deploy a highly scalable and performance-oriented database. MongoDB features are flexible data models that allows the storage of unstructured data. This provides full support indexing, replication, capabilities and also user friendly APIs. The MongoDB is a multipurpose dataset that is used for modern application development and cloud environments. This scalable architecture enables us to handle system demands and also adding more nodes to distribute the load. MongoDB is an open source NOSQL dataset in C++, this offers flexible data models, indexing, replication and modern applications for scalable architecture. MongoDB Basic Commands We have a list of standard MongoDb commands to interact with the database, These commands are CREATE, READ, INSERT, UPDATE, DELETE, DROP and AGGREGATE can be classified into following groups based on their nature − Command Description CREATE Creates a new table in the database and other objects in the database. INSERT Inserts collection name in existing database. DROP Deletes an entire table or specified objects in the database. UPDATE Updates the document into a collection. Why to Learn MongoDB? MongoDB can handle unstructured data, which provides better indexing and operations. MongoDB ensures the development software applications that can handle all sorts of data in a scalable way. MongoDB is a rapid iterative development that enables the collaboration of a large number of teams. MongoDB has become the most necessary database in the world, which makes it easy for every developer to store, manage, and retrieve data. MongoDB Applications MongoDB is a NoSQL database. MongoDB provides following functionality to the database programmers − Stores user data, comments and metadata MongoDB performs complex analytics queries and stores the behavioral data. This is used to manage chain data and optimize logistics. Environmental data and IoT devices are stored and analyzed. Who Should Learn MongoDB This MongoDB tutorial will help web developers, devops engineer, mobile apps, backend, full-stack, database administrators, etc. We recommend reading this tutorial, in the sequence listed in the left side menu. Prerequisites to Learn MongoDB Before 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 high performance database, so it will be good if you have an understanding on the basic concepts of Database (RDBMS). MongoDB is typically used in the development of applications, at least one programming language is very helpful to work with APIs. MongoDB Jobs and Opportunities MongoDB is in high demand professionally and it is exponentially growing in the IT industry. In MongoDB jobs are in high demand with a growth rate of 50%. The NoSQL database market is growing at a rate of 30%. Average salaries for a MongoDB professional are around $100,000 to $200,000. This may vary depending on the location. The Following companies recruit MongoDB professionals: Accenture IBM Deloitte Capgemini TCS Infosys Wipro Google Amazon Microsoft HCL You could be the next employee for any of these major companies. We have developed great learning material for MongoDB that helps you prepare for technical interviews and certifications. So, start learning MongoDB using our tutorial anywhere and anytime, absolutely at your place. Frequently Asked Questions about MongoDB There are some very Frequently Asked Questions(FAQ) about MongoDB, this section tries to answer them briefly. What is MongoDB and its uses? MangoDB can manage document information, stores and retrieves the information. This is used for high data storage and performing large amount of data while performing the dataset. This is a distributed database at its level, high availability, horizontal scaling are built in and easy to use. Can you explain the concept of sharding in MongoDB? Sharding is a database that separates large database into smaller, faster, and easily managed parts. These smaller parts are called data shards. Shard is defined as a “small part of a whole”. What type of language is MongoDB? MongoDB is not a programming language, but this is a NOSQL database. This query language allows us to interact with the data. MongoDB is a non-relational database management system that stores the data in flexible JSON documents. What are the limitations of MongoDB? This supports multi-document transactions, even though they are less performed as compared to traditional relational databases. This can be used in memory intensive situation because memory maps the entire data file into memory. This is designed for eventual consistency, which means there can be a lag before all the nodes in a distributed system. Can I learn MongoDB without SQL? Yes, you can learn MongoDB without knowledge of SQL. MongoDB uses its own query language, which is different from SQL. You need to learn about NoSQL databases, and these vary very much from the SQL database. MongoDB Compass is a user-friendly interface that visualizes your data and understands your schema without using the command line. What platforms does MongoDB support? MongoDB supports wide range of platforms, that are useful for developing various environments. Operating System performs Windows 7 and Linux with various distributions. Cloud Platform in MongoDB manages data-base-as-a-service available in Google, AWS and Azure. Docker provides the official Docker images for deployment. What are indexes in MongoDB? Following are MongoDB Indexes. Single Field Index. Compound Index. Multikey Index. Text Index. Hashed Index. What is a primary key in MongoDB? MongoDB implements the primary key using the ”_id” field. Every primary key acts as a different identifier for the document. This field is automatically created by MongoDB when the document is inserted. This can be any type, as long as it is different from the collection. Print Page Previous