{"id":27451,"date":"2022-02-27T15:23:02","date_gmt":"2022-02-27T15:23:02","guid":{"rendered":"https:\/\/www.askpython.com\/?p=27451"},"modified":"2023-04-04T14:23:14","modified_gmt":"2023-04-04T14:23:14","slug":"python-mongodb","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/python-mongodb","title":{"rendered":"Python MongoDB &#8211; A Complete Overeview"},"content":{"rendered":"\n<p>MongoDB is one of the most popular non-relational (also known as NoSQL database) databases. Non-relational or NoSQL databases do not have a fixed table structure or schema to be followed which makes the database very flexible and scalable. The data in NoSQL databases are stored in JSON-like format known as RSON. MongoDB is very convenient to use while dealing with large and unstructured data and hence it is the most widely used database in data analysis. It offers high speed and availability. In this article, let us see how can we connect our python script to MongoDB and perform desired operations.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"python-driver\">Python MongoDB Driver<\/h2>\n\n\n\n<p>PyMongo is the native driver for connecting MongoDB and python. PyMongo has all the libraries to perform database operations from python code. Since pymongo is a low-level driver, it is fast and intuitive and provides more control. To install PyMongo, open your command line and type in the following command<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nC:\\Users\\Your Name\\AppData\\Local\\Programs\\Python\\Python36-32\\Scripts&gt;python -m pip install pymongo\n<\/pre><\/div>\n\n\n<p>This command would install PyMongo. We could install PyMongo in our script and start accessing the MongoDB resources.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"mongodb-databases\">MongoDB databases<\/h2>\n\n\n\n<p>Now let us create a database in MongoDB. We will use the MongoClient() class of PyMongo to create the database. We will pass the correct localhost IP address and post to create the database. And use the client to give a desired name to the database.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nfrom pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient(&#039;localhost&#039;, 27017)\n\n#Getting the database instance\ndb = client&#x5B;&#039;mongodb1&#039;]\nprint(&quot;Database created.&quot;)\n\n#Verify the database\nprint(&quot;List of existing databases&quot;)\nprint(client.list_database_names())\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"output\">Output<\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\">Database created.\nList of existing databases:\n['admin', 'config', 'local', 'mongodb1']<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"creating-a-collection\">Creating a Collection<\/h2>\n\n\n\n<p>Inside a database, we can create multiple collections Collections can be compared to tables of the conventional database and we can store multiple records in the collection. Now, let us see how to create a collection inside a database. Also, note that our collection gets created when at least one document is inserted into it.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n#create a collection named &quot;students&quot;\nmycol = mydb&#x5B;&quot;students&quot;]\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"insert-into-collection\">Insert into Collection<\/h2>\n\n\n\n<p>Records are called documents in MongoDB. To insert a document into the collection, we should use the insert_one() method. We can pass the created document as an argument in the insert_one method. Let us understand how to insert a document with an example.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n#create a document\ntest = { &quot;name&quot;: &quot;Ripun&quot;, &quot;class&quot;: &quot;Seventh&quot; }\n\n#insert a document to the collection\nx = mycol.insert_one(test)\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"inserting-multiple-records\">Inserting multiple records<\/h2>\n\n\n\n<p>To insert multiple records into a collection, we can use insert_many() method. To implement this, we will first create a list with multiple documents and pass them on to insert_many() method.<\/p>\n\n\n\n<p>mylist = [<br>&nbsp; {&nbsp;&#8220;name&#8221;:&nbsp;&#8220;Amy&#8221;,&nbsp;&#8220;class&#8221;:&nbsp;&#8220;Seventh&#8221;},<br>&nbsp;&nbsp;{&nbsp;&#8220;name&#8221;:&nbsp;&#8220;Hannah&#8221;,&nbsp;&#8220;class&#8221;:&nbsp;&#8220;Sixth&#8221;},<br>&nbsp; {&nbsp;&#8220;name&#8221;:&nbsp;&#8220;Viola&#8221;,&nbsp;&#8220;class&#8221;:&nbsp;&#8220;Sixth&#8221;}]                                                                                                                                           x= mycol.insert_many(mylist)<\/p>\n\n\n\n<p>We can also insert them with their ids.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nmylist = &#x5B; {\u00a0&quot;_id&quot;:1,&quot;name&quot;:\u00a0&quot;Amy&quot;,\u00a0&quot;class&quot;:\u00a0&quot;Seventh&quot;},\n\u00a0\u00a0{\u00a0&quot;_id&quot;:2,&quot;name&quot;:\u00a0&quot;Hannah&quot;,\u00a0&quot;class&quot;:\u00a0&quot;Sixth&quot;},\n\u00a0 {\u00a0&quot;_id&quot;:3,&quot;name&quot;:\u00a0&quot;Viola&quot;,\u00a0&quot;class&quot;:\u00a0&quot;Sixth&quot;}]   \n\nx = mycol.insert_many(mylist)\n\nprint(x.inserted_ids)\n\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"accessing-the-documents-from-collection\">Accessing the documents from collection<\/h2>\n\n\n\n<p>Now once the collection is structured and loaded with data, we would want to access them based on our requirements. To access the data, we can use the find() method. <\/p>\n\n\n\n<p>find_one() method returns the first occurrence in the collection.  <\/p>\n\n\n\n<p>find() method returns all the occurrences in the collection. find() method when used without any parameter behaves the same way as Select all in SQL.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"output-1\">Output<\/h2>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nx = mycol.find_one()\n\n# This prints the first document\nprint(x)\n\nfor x in mycol.find():\n  print(x)\n<\/pre><\/div>\n\n\n<p>Sometimes, we would want to retrieve only particular fields of the document. To include the field in the result the value of the parameter passed should be 1, if the value is 0 then it will be excluded from the result.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nfor x in mycol.find({},{ &quot;_id&quot;: 0, &quot;name&quot;: 1, &quot;class&quot;: 1 }):\n  print(x)\n<\/pre><\/div>\n\n\n<p>The above code will just return the name and the class field from our collection and excludes the id field.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"queries\">Querying the MongoDB Database <\/h2>\n\n\n\n<p>We can use find() to retrieve results in more refined way by using the query object. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"operators\">Operators<\/h3>\n\n\n\n<p>Following is the list of operators used in the queries in MongoDB.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><th>Operation<\/th><th>Syntax<\/th><th>Example<\/th><\/tr><tr><td>Equality<\/td><td>{&#8220;key&#8221; : &#8220;value&#8221;}<\/td><td>db.mycol.find({&#8220;by&#8221;:&#8221;tutorials point&#8221;})<\/td><\/tr><tr><td>Less Than<\/td><td>{&#8220;key&#8221; :{$lt:&#8221;value&#8221;}}<\/td><td>db.mycol.find({&#8220;likes&#8221;:{$lt:50}})<\/td><\/tr><tr><td>Less Than Equals<\/td><td>{&#8220;key&#8221; :{$lte:&#8221;value&#8221;}}<\/td><td>db.mycol.find({&#8220;likes&#8221;:{$lte:50}})<\/td><\/tr><tr><td>Greater Than<\/td><td>{&#8220;key&#8221; :{$gt:&#8221;value&#8221;}}<\/td><td>db.mycol.find({&#8220;likes&#8221;:{$gt:50}})<\/td><\/tr><tr><td>Greater Than Equals<\/td><td>{&#8220;key&#8221; {$gte:&#8221;value&#8221;}}<\/td><td>db.mycol.find({&#8220;likes&#8221;:{$gte:50}})<\/td><\/tr><tr><td>Not Equals<\/td><td>{&#8220;key&#8221;:{$ne: &#8220;value&#8221;}}<\/td><td>db.mycol.find({&#8220;likes&#8221;:{$ne:50}})<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p id=\"example-code\"><strong>Example Code:<\/strong><\/p>\n\n\n\n<p>The following code retrieves the document where the name field is Sathish.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nfrom pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient(&#039;localhost&#039;, 27017)\n\n#Getting the database instance\ndb = client&#x5B;&#039;sdsegf&#039;]\n\n#Creating a collection\ncoll = db&#x5B;&#039;example&#039;]\n\n#Inserting document into a collection\ndata = &#x5B;\n   {&quot;_id&quot;: &quot;1001&quot;, &quot;name&quot;: &quot;Ram&quot;, &quot;age&quot;: &quot;26&quot;, &quot;city&quot;: &quot;Hyderabad&quot;},\n   {&quot;_id&quot;: &quot;1002&quot;, &quot;name&quot;: &quot;Mukesh&quot;, &quot;age&quot;: &quot;27&quot;, &quot;city&quot;: &quot;Bangalore&quot;},\n   {&quot;_id&quot;: &quot;1003&quot;, &quot;name&quot;: &quot;Vel&quot;, &quot;age&quot;: &quot;28&quot;, &quot;city&quot;: &quot;Mumbai&quot;},\n   {&quot;_id&quot;: &quot;1004&quot;, &quot;name&quot;: &quot;Sathish&quot;, &quot;age&quot;: &quot;25&quot;, &quot;city&quot;: &quot;Pune&quot;},\n   {&quot;_id&quot;: &quot;1005&quot;, &quot;name&quot;: &quot;Rashiga&quot;, &quot;age&quot;: &quot;23&quot;, &quot;city&quot;: &quot;Delhi&quot;},\n   {&quot;_id&quot;: &quot;1006&quot;, &quot;name&quot;: &quot;Priya&quot;, &quot;age&quot;: &quot;26&quot;, &quot;city&quot;: &quot;Chennai&quot;}\n]\nres = coll.insert_many(data)\nprint(&quot;Data inserted ......&quot;)\n\n#Retrieving data\nprint(&quot;Documents in the collection: &quot;)\n\nfor doc1 in coll.find({&quot;name&quot;:&quot;Sathish&quot;}):\n   print(doc1)\n<\/pre><\/div>\n\n\n<p id=\"output-2\"><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Data inserted ......\nDocuments in the collection:\n{'_id': '1004', 'name': 'Sathish', 'age': '25', 'city': 'Pune'}\n<\/pre>\n\n\n\n<p>Now let us retrieve the records with persons whose age is greater than 25. We will use the $gt operator to implement it.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">for doc in coll.find({\"age\":{\"$gt\":\"25\"}}):\n   print(doc)<\/pre>\n\n\n\n<p id=\"output-3\"><strong>Output<\/strong><\/p>\n\n\n\n<p>{&#8220;_id&#8221;: &#8220;1002&#8221;, &#8220;name&#8221;: &#8220;Mukesh&#8221;, &#8220;age&#8221;: &#8220;27&#8221;, &#8220;city&#8221;: &#8220;Bangalore&#8221;}<br>{&#8220;_id&#8221;: &#8220;1003&#8221;, &#8220;name&#8221;: &#8220;Vel&#8221;, &#8220;age&#8221;: &#8220;28&#8221;, &#8220;city&#8221;: &#8220;Mumbai&#8221;}<\/p>\n\n\n\n<p>In the similar fashion, we can use $lt to filter the records with the value lesser than our specified value. We can also use these operators on a string. For example when we use &#8220;name&#8221;:{&#8220;$gt&#8221;:&#8221;J&#8221;} to retrieve all the records with names starting with &#8216;J&#8217; or with the alphabets after that.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"delete-operation\">Delete Operation in Python MongoDB<\/h2>\n\n\n\n<p>We can use the delete_one() method to delete one document.<\/p>\n\n\n\n<p>The first parameter of the\u00a0<code>delete_one()<\/code>\u00a0method is a query object which indicates the document to be deleted.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nmyquery = {&quot;name&quot; : &quot;Mukesh&quot;}\n\ncoll.delete_one(myquery)\n<\/pre><\/div>\n\n\n<p>To delete multiple documents, we can use the delete_many() method.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nmyquery = { &quot;name&quot;: {&quot;$regex&quot;: &quot;^S&quot;} }\n\nx = coll.delete_many(myquery)\n\n<\/pre><\/div>\n\n\n<p>The above code will delete all the records where the person&#8217;s name starts with &#8216;S&#8217; or the letters that are alphabetically placed after S.<\/p>\n\n\n\n<p>To delete all documents in a collection,  we can pass an empty query object to the\u00a0<code>delete_many()<\/code>\u00a0method.  The below code will delete all the documents present in the collection.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nx = coll.delete_many({})\n<\/pre><\/div>\n\n\n<p>If we would want to delete the whole  collection itself, we can use the drop() method. <\/p>\n\n\n\n<p>coll.drop()<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"conclusion\">Conclusion<\/h2>\n\n\n\n<p>In this article, we have seen about connecting MongoDB to python and performing various required and essential operations on it. The readers are strongly encouraged to get some hands-on experience with MongoDB and make themselves familiar on the syntax and various queries.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"references\">References<\/h2>\n\n\n\n<p><a href=\"https:\/\/www.mongodb.com\/languages\/python\" target=\"_blank\" rel=\"noopener\">https:\/\/www.mongodb.com\/languages\/python<\/a><\/p>\n\n\n\n<p><a href=\"https:\/\/www.mongodb.com\/docs\/drivers\/python\/\" target=\"_blank\" rel=\"noopener\">https:\/\/docs.mongodb.com\/drivers\/python\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>MongoDB is one of the most popular non-relational (also known as NoSQL database) databases. Non-relational or NoSQL databases do not have a fixed table structure or schema to be followed which makes the database very flexible and scalable. The data in NoSQL databases are stored in JSON-like format known as RSON. MongoDB is very convenient [&hellip;]<\/p>\n","protected":false},"author":40,"featured_media":27634,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-27451","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-modules"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/27451","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/40"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=27451"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/27451\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/27634"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=27451"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=27451"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=27451"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}