{"id":104151,"date":"2024-11-05T18:13:00","date_gmt":"2024-11-05T18:13:00","guid":{"rendered":"https:\/\/www.red-gate.com\/simple-talk\/?p=104151"},"modified":"2024-11-14T22:03:52","modified_gmt":"2024-11-14T22:03:52","slug":"connecting-to-mongodb-through-python","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/databases\/nosql\/mongodb\/connecting-to-mongodb-through-python\/","title":{"rendered":"Connecting to MongoDB through Python"},"content":{"rendered":"<p><strong>This article is part of Robert Sheldon's continuing series on Mongo DB. To see all of the items in the series, <a href=\"https:\/\/www.red-gate.com\/simple-talk\/collections\/robert-sheldon-ongoing-mongodb-primer\/\">click here<\/a>.<\/strong><\/p>\n\n<p>This article is a bit of a departure from the previous articles in this series. Rather than focusing exclusively on MongoDB, I explain how to access MongoDB through the Python programming language. Many data-driven applications rely on MongoDB for their data, including those written in Python, and I think it\u2019s important to understand how data can be accessed and modified from within an application. Covering this topic also helps to round out the series so you a more complete picture of MongoDB in the real-world.<\/p>\n<p>Python is one of multiple languages through which you can access MongoDB data. I chose Python because the language makes it relatively easy to demonstrate different ways to interface with a MongoDB database and collection. This article walks you through the process of creating Python scripts that let you connect to a MongoDB database and carry out create, read, update, and delete (CRUD) operations.<\/p>\n<p>This article is by no means intended to be an exhaustive discussion of how to access MongoDB data in an application. It is meant only to provide you with the basics you need to get started with Python and to give you a general sense of what it takes to work with MongoDB in a programming language. The exact approach you\u2019ll need to take will depend on the particular language you\u2019re working in and the driver used to interface with a MongoDB database.<\/p>\n<p>Throughout the article, I provide multiple examples that demonstrate how to connect to Atlas MongoDB and perform CRUD operations. The examples are based on the PyMongo driver, which you must install on your system if you want to try out the examples for yourself. For details about PyMongo, refer to the <a href=\"https:\/\/www.mongodb.com\/docs\/languages\/python\/pymongo-driver\/current\/\">MongoDB PyMongo Documentation<\/a>. This article assumes that you\u2019re already familiar with Python and have it installed on your system. With that in mind, let\u2019s get started.<\/p>\n<p>Note: For the examples in this article, I used the same MongoDB Atlas environment I used for the previous articles in this series. Refer to the first article for details about setting up these environments. The examples also require the <code>hr<\/code> database to be in place if you want to try them out for yourself.<\/p>\n<h2>Connecting to MongoDB through Python<\/h2>\n<p>To access MongoDB documents from within an application, you must establish a connection to the target MongoDB server and the specific database. The exact approach depends on the programming language and the driver you use to facilitate communications between the client and the server. As already noted, we\u2019ll be using be using Python and the PyMongo driver for this article.<\/p>\n<p>All the examples will use the same basic construction to establish a connection with the server and database. Each script will define the connection, connect to the <code>hr<\/code> database, run a query against the database, and close the connection. The following script shows the necessary language elements to carry out these operations, without the actual query:<\/p>\n<pre class=\"lang:none theme:none\">from pymongo import MongoClient\nfrom pymongo.server_api import ServerApi\nconn = <em>&lt;connection_string&gt;<\/em>\nclient = MongoClient(conn, &lt;<em>client_settings<\/em>&gt;)\ntry:\n  db = client.get_database(\"hr\")\n  # start query\n  \n  <em>&lt;query&gt;<\/em>\n  # end query\n  client.close()\nexcept Exception as e:\n  raise Exception(\"MongoDB returned the following error: \", e)<\/pre>\n<p>I\u2019ll go through each command and explain how it works, but first I want to point out the <code>&lt;query&gt;<\/code> placeholder, sandwiched between the <code>#<\/code> <code>start<\/code> <code>query<\/code> and <code>#<\/code> <code>end<\/code> <code>query<\/code> comments. For each example that follows, you\u2019ll simply switch out the placeholder for the query itself.<\/p>\n<p>The first two commands in the script import the <code>MongoClient<\/code> class and <code>ServerApi<\/code> class from the <code>pymongo<\/code> module, making it possible to establish a connection to a MongoDB server:<\/p>\n<pre class=\"lang:none theme:none\">from pymongo import MongoClient\nfrom pymongo.server_api import ServerApi<\/pre>\n<p>The second <code>import<\/code> statement might not be necessary, depending on how you define the <code>MongoClient<\/code> object. I\u2019ll discuss this in more detail shortly. But first, take a look at the next command, which defines a connection string and assigns it to the <code>conn<\/code> variable:<\/p>\n<pre class=\"lang:none theme:none\">conn = <em>&lt;connection_string&gt;<\/em><\/pre>\n<p>You can use whatever variable name you like. A lot of documentation uses <code>uri<\/code> because you\u2019re defining a URI connection to the MongoDB server.<\/p>\n<p>The connection string itself depends on the target MongoDB server. For MongoDB Atlas, the simplest way to define the connection string is to copy the one available through the Atlas interface, as explained in the <a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/nosql\/getting-started-with-mongodb\/\">first article<\/a> in this series.<\/p>\n<p>Note, however, that the first article walks you through the process of retrieving the connection string for MongoDB Compass. For this article, you should select the connection string specific to Python, inserting your password as appropriate. To find the connection string, navigate to your cluster in Atlas and click the <strong>Connect<\/strong> button. In the <strong>Connect<\/strong> <strong>to<\/strong> dialog box, click <strong>Drivers<\/strong> and then select <strong>Python<\/strong> from the <strong>Driver<\/strong> drop-down list. You\u2019ll find the connection string under Step 3.<\/p>\n<p>If you\u2019re connecting to MongoDB on a local machine, you should be able to use the following connection string when assigning the <code>conn<\/code> variable:<\/p>\n<pre class=\"lang:none theme:none\">conn = mongodb:\/\/localhost:27017\/<\/pre>\n<p>After you define your connection string, you must initialize a new instance of the <code>MongoClient<\/code> class. You can find an example of how to instantiate the class in the same place in Atlas where you found the connection string. (To do so, you must view the full code sample, rather than just the connection stream.) The instantiation command takes the following form:<\/p>\n<pre class=\"lang:none theme:none\">client = MongoClient(conn, server_api=ServerApi('1'))<\/pre>\n<p>The command creates a <code>MongoClient<\/code> object and assigns it to the <code>client<\/code> variable. To create the object, the code uses the <code>MongoClient<\/code> constructor and passes in two arguments to the constructor. The first argument is the <code>conn<\/code> variable, which provides the constructor with the necessary connection information.<\/p>\n<p>The second argument, <code>server_api<\/code>, is optional. It specifies which server API version to use when creating the <code>MongoClient<\/code> object. This is important if you want to ensure that the driver always conforms to a specific API version. To specify the version, you must use the <code>ServerApi<\/code> constructor to create a <code>ServerApi<\/code> object. According to MongoDB documentation and the Atlas site itself, you should use <code>1<\/code> as the constructor\u2019s argument when connecting to Atlas.<\/p>\n<p>If you\u2019re not concerned about enforcing a specific API version, you need only include the <code>conn<\/code> variable as the <code>MongoClient<\/code> constructor\u2019s argument:<\/p>\n<pre class=\"lang:none theme:none\">client = MongoClient(conn)<\/pre>\n<p>When you take this approach, you can omit the second <code>import<\/code> statement at the beginning of your script. The statement imports the <code>ServerApi<\/code> class, which is not needed if it\u2019s not referenced as an argument in the <code>MongoClient<\/code> method.<\/p>\n<p>The remaining components in the base code include a <code>try<\/code> block that contains the main code, followed by an <code>except<\/code> block that handles any errors.<\/p>\n<p>The first command in the <code>try<\/code> block uses the <code>client<\/code> variable to call the <code>get_database<\/code> method available to the <code>MongoClient<\/code> object:<\/p>\n<pre class=\"lang:none theme:none\">db = client.get_database(\"hr\")<\/pre>\n<p>The method\u2019s only argument is the name of the target database, which in this case is <code>hr<\/code>. The database object returned by the method is saved to the <code>db<\/code> variable. You can use the variable to access methods available to the database object when working with the <code>hr<\/code> database.<\/p>\n<p>The <code>try<\/code> block then includes the comments and <code>&lt;query&gt;<\/code> placeholder mentioned earlier. Next comes the following command, which specifies the <code>close<\/code> method to end the client connection:<\/p>\n<pre class=\"lang:none theme:none\">client.close()<\/pre>\n<p>The <code>except<\/code> block catches any exceptions and saves them to the <code>e<\/code> variable, which is then used in the error message defined by the <code>Exception<\/code> method:<\/p>\n<pre class=\"lang:none theme:none\">except Exception as e:\n  raise Exception(\"MongoDB returned the following error: \", e)<\/pre>\n<p>That\u2019s all there is to creating the basic shell we need for the rest of the article. As already noted, you\u2019ll be replacing the <code>&lt;query&gt;<\/code> placeholder with the code in the following examples. The base elements will remain the same throughout.<\/p>\n<h2>Creating a collection in a MongoDB database through Python<\/h2>\n<p>Now that we have our base code in place, let\u2019s look at how to work with the target database. The following example creates a collection in the <code>hr<\/code> database and then retrieves a list of the collections defined in the database:<\/p>\n<pre class=\"lang:none theme:none\">db.create_collection(\"personnel\")\ncollections = db.list_collection_names()\nfor collection in collections:\n  print(collection)<\/pre>\n<p>The first command uses the <code>create_collection<\/code> method available the database object to create the <code>personnel<\/code> collection in the <code>hr<\/code> database. You can call the method though the <code>db<\/code> variable, passing in the collection name as an argument to the method.<\/p>\n<p>The second command uses the <code>list_collection_names<\/code> method available the database object to retrieve the names of the database\u2019s current collections. The command saves the list of collections to the <code>collections<\/code> variable.<\/p>\n<p>The third command is a <code>for<\/code> statement that iterates though the <code>collections<\/code> list. For each iteration, the current collection name is saved to the <code>collection<\/code> variable. The <code>print<\/code> command then print\u2019s the variable\u2019s value to the screen.<\/p>\n<p>When you replace the <code>&lt;query&gt;<\/code> placeholder in the base code with the above code, it should look like the following script:<\/p>\n<pre class=\"lang:none theme:none\">from pymongo import MongoClient\nfrom pymongo.server_api import ServerApi\nconn = <em>&lt;connection_string&gt;<\/em>\nclient = MongoClient(conn, &lt;<em>client_settings<\/em>&gt;)\ntry:\n  db = client.get_database(\"hr\")\n  # start query\n  \n  db.create_collection(\"personnel\")\n  collections = db.list_collection_names()\n  for collection in collections:\n    print(collection)\n  # end query\n  client.close()\nexcept Exception as e:\n  raise Exception(\"MongoDB returned the following error: \", e)<\/pre>\n<p>If you save this script to a text file (with a <code>.py<\/code> extension), you should be able to run it at a command prompt. If you\u2019re not sure how to run a Python script, refer to the Python documentation. The process is usually fairly straightforward once you\u2019ve installed Python. Your shell command might take a form similar to the following:<\/p>\n<pre class=\"lang:none theme:none\">&gt; python &lt;<em>file_path<\/em>&gt;\/&lt;<em>file_name<\/em>&gt;.py<\/pre>\n<p>When you run the script, it should return a list of the existing collections, which will be specific to your MongoDB instance. At the very least, the results should include the newly created <code>personnel<\/code> collection.<\/p>\n<p>When I first tried to run this script on my Mac computer, I received a certificate verification error. I was able to resolve the issue by running the following command file, which was available in my Python installation folder:<\/p>\n<pre class=\"lang:none theme:none\">\/Applications\/Python\\ 3.10\/Install\\ Certificates.command<\/pre>\n<p>If you run into this issue when connecting to Atlas, you might be able to take a similar approach to resolve it. I did not run into this issue when trying to connect to a local instance of MongoDB.<\/p>\n<h2>Adding documents to a MongoDB database through Python<\/h2>\n<p>Now that we\u2019ve gotten the basics out of the way, we can move onto using Python to carry out standard CRUD operations, starting with how to insert data. In the following example, the code adds a single document to the <code>personnel<\/code> collection and then prints the results returned by MongoDB:<\/p>\n<pre class=\"lang:none theme:none\">personnel = db.get_collection(\"personnel\")\ndoc = { \"_id\": 101, \"name\": \"Drew\", \"position\": \"Senior Developer\", \"dept\": \"R&amp;D\" }\nresults = personnel.insert_one(doc)\nprint(results)<\/pre>\n<p>The first command uses the <code>get_collection<\/code> method available the <code>db<\/code> database object to create a collection object for the <code>personnel<\/code> collection. The command then assigns the object to the <code>personnel<\/code> variable. You can then use the variable to run methods available to the collection object.<\/p>\n<p>The second command defines the document to be inserted into the collection and assigns it to the <code>doc<\/code> variable. This is a straightforward document definition just like you\u2019ve seen in previous articles. In this case, I\u2019ve kept the document very simple, but you can define any type of documents.<\/p>\n<p>The next command uses the <code>insert_one<\/code> method available to the collection object to add the document to the collection. The <code>doc<\/code> variable is passed in as an argument to the method. When the method is executed, the document is added to the collection. The results returned by MongoDB are assigned to the <code>results<\/code> variable.<\/p>\n<p>The final command prints the information that was assigned to the <code>results<\/code> variable. When you run the script, it should return the following results:<\/p>\n<pre class=\"lang:none theme:none\">InsertOneResult(101, acknowledged=True)<\/pre>\n<p>There might be times when you want to add multiple documents to a collection in a single operation. For the most part, you use the same format as with a single document, with a couple notable differences, as shown in the following example:<\/p>\n<pre class=\"lang:none theme:none\">  personnel = db.get_collection(\"personnel\")\ndocs = [\n  { \"_id\": 102, \"name\": \"Parker\", \"position\": \"Data Scientist\", \"dept\": \"R&amp;D\" },\n  { \"_id\": 103, \"name\": \"Harper\", \"position\": \"Marketing Manager\", \"dept\": \"Marketing\" },\n  { \"_id\": 104, \"name\": \"Darcy\", \"position\": \"Senior Developer\", \"dept\": \"R&amp;D\" },\n  { \"_id\": 105, \"name\": \"Carey\", \"position\": \"SEO Specialist\", \"dept\": \"Marketing\" },\n  { \"_id\": 106, \"name\": \"Avery\", \"position\": \"Network Admin\", \"dept\": \"IT\" },\n  { \"_id\": 107, \"name\": \"Robin\", \"position\": \"Security Specialist\", \"dept\": \"IT\" },\n  { \"_id\": 108, \"name\": \"Koda\", \"position\": \"QA Specialist\", \"dept\": \"R&amp;D\" },\n  { \"_id\": 109, \"name\": \"Jessie\", \"position\": \"Brand Manager\", \"dept\": \"Marketing\" },\n  { \"_id\": 110, \"name\": \"Dana\", \"position\": \"Market Analyst\", \"dept\": \"Marketing\" }\n]\nresults = personnel.insert_many(docs)\nprint(results)<\/pre>\n<p>As before, you start by assigning the collection object to the <code>personnel<\/code> variable. Next, you define an array that contains the document definitions. In this case, there are nine documents whose <code>_id<\/code> values range from <code>102<\/code> through <code>110<\/code>. Because it is an array, the documents are enclosed in square brackets, with commas separating the individual documents. The array is then assigned to the <code>docs<\/code> variable.<\/p>\n<p>The next command uses the <code>insert_many<\/code> method available to the collection object to add the documents to the collection, referencing the documents through the <code>docs<\/code> variable. The command then saves the results returned by MongoDB to the <code>results<\/code> variable.<\/p>\n<p>As before, the final step prints the information that was assigned to the <code>results<\/code> variable. The command should return the following results:<\/p>\n<pre class=\"lang:none theme:none\">InsertManyResult([102, 103, 104, 105, 106, 107, 108, 109, 110], acknowledged=True)<\/pre>\n<p>The nine documents have now been added to the <code>personnel<\/code> collection, which already contained the one added in the previous example, giving you a total of 10 documents.<\/p>\n<h2>Retrieving documents from a MongoDB database through Python<\/h2>\n<p>The process of retrieving documents is just as straightforward as adding them. You can retrieve a single document or multiple documents, using the same type of query expressions you\u2019ve seen in earlier articles. For example, the following code retrieves a document with an <code>_id<\/code> value of <code>102<\/code> from the <code>personnel<\/code> collection:<\/p>\n<pre class=\"lang:none theme:none\">personnel = db.get_collection(\"personnel\")\nquery = { \"_id\": 102 }\nresults = personnel.find_one(query)\nprint(results)<\/pre>\n<p>After assigning the collection object to the <code>personnel<\/code> variable, the code defines a simple query that limits the results to documents with an <code>_id<\/code> value of <code>102<\/code>. Because the query specifies the <code>_id<\/code> field, you know that the value <code>102<\/code> is unique and that there will be only one document. The query is then assigned to the <code>query<\/code> variable.<\/p>\n<p>The next command uses the <code>find_one<\/code> method available to the collection object to retrieve the target document, using the query assigned to the <code>query<\/code> variable. The command also saves the results returned by MongoDB to the <code>results<\/code> variable. The last command prints the information in the <code>results<\/code> variable. When you run the script, MongoDB should return the following document, which is the one that matches the search criteria:<\/p>\n<pre class=\"lang:none theme:none\">{'_id': 102, 'name': 'Parker', 'position': 'Data Scientist', 'dept': 'R&amp;D'}<\/pre>\n<p>The <code>find_one<\/code> method returns only the first document returned by the query, even if multiple documents satisfy the search condition. However, you can return all documents by using the <code>find<\/code> method instead of <code>find_one<\/code>, as in the following example:<\/p>\n<pre class=\"lang:none theme:none\">personnel = db.get_collection(\"personnel\")\nquery = { \"dept\": \"Marketing\" }\nresults = personnel.find(query)\nfor result in results:\n  print(result)<\/pre>\n<p>The query now specifies that any returned documents must have a <code>dept<\/code> value of <code>Marketing<\/code>. In addition, the code uses the <code>find<\/code> method to return all matching documents, again saving the returned documents to the <code>results<\/code> variable.<\/p>\n<p>Next, the code includes a <code>for<\/code> statement that iterates through the documents in the <code>results<\/code> variable. For each iteration, the statement assigns the current document to the <code>result<\/code> variable and print\u2019s the variable\u2019s value to the screen, giving us the following results:<\/p>\n<pre class=\"lang:none theme:none\">{'_id': 103, 'name': 'Harper', 'position': 'Marketing Manager', 'dept': 'Marketing'}\n{'_id': 105, 'name': 'Carey', 'position': 'SEO Specialist', 'dept': 'Marketing'}\n{'_id': 109, 'name': 'Jessie', 'position': 'Brand Manager', 'dept': 'Marketing'}\n{'_id': 110, 'name': 'Dana', 'position': 'Market Analyst', 'dept': 'Marketing'}<\/pre>\n<p>You can also define aggregations in your queries, similar to what you saw in earlier articles. For this, you should first define a pipeline and assign it to a variable, as in the following example:<\/p>\n<pre class=\"lang:none theme:none\">personnel = db.get_collection(\"personnel\")\npipeline = [\n  { \"$match\": { \"$or\": [ { \"dept\": \"R&amp;D\" }, { \"dept\": \"Marketing\" } ] } },\n  { \"$group\": { \"_id\": \"$dept\", \"count\": { \"$sum\": 1 } } }\n]\nresults = personnel.aggregate(pipeline)\nfor result in results:\n  print(result)<\/pre>\n<p>The pipeline uses the <code>$match<\/code> stage to return only those documents with a <code>dept<\/code> value of <code>R&amp;D<\/code> or <code>Marketing<\/code>. The <code>$group<\/code> stage then groups the results by the <code>dept<\/code> field and returns a count of the number of documents in each group. The entire pipeline definition is assigned to the <code>pipeline<\/code> variable.<\/p>\n<p>The next command uses the <code>aggregate<\/code> method available to the collection object to aggregate the data, using the pipeline definition assigned to the <code>pipeline<\/code> variable. The command also saves the returned data to the <code>results<\/code> variable. All this is followed by a <code>for<\/code> loop that iterates through the results and returns the following information:<\/p>\n<pre class=\"lang:none theme:none\">{'_id': 'Marketing', 'count': 4}\n{'_id': 'R&amp;D', 'count': 4}<\/pre>\n<p>The results include the group name and the number of documents in each group, which translates to the number of employees in each department, as reflected by the <code>personnel<\/code> collection. You can, of course, define much more complex pipelines, just like you can define more complex queries when working with the <code>find_one<\/code> and <code>find<\/code> methods.<\/p>\n<h2>Updating documents in a MongoDB database through Python<\/h2>\n<p>You can also use Python to modify your documents, updating either one document or multiple documents in a single operation. When you update the documents, you must specify a query expression that determines which documents to update and then an update expression that defines how to update them.<\/p>\n<p>For example, the following code updates the document with an <code>_id<\/code> value of <code>104<\/code>, changing the value of the <code>position<\/code> field to <code>Developer<\/code>:<\/p>\n<pre class=\"lang:none theme:none\">personnel = db.get_collection(\"personnel\")\nquery = { \"_id\": 104 }\nupdate = { \"$set\": { \"position\": \"Developer\" } }\nresults = personnel.update_one(query, update)\nprint(results)<\/pre>\n<p>The query portion is similar to what you saw when retrieving documents. The expression specifies that the target document must have an <code>_id<\/code> value of <code>104<\/code>. The expression is then assigned to the <code>query<\/code> variable. Next, the update expression uses the <code>$set<\/code> operator to set the <code>position<\/code> value to <code>Developer<\/code>. This expression is assigned to the <code>update<\/code> variable.<\/p>\n<p>The fourth command uses the <code>update_one<\/code> method available to the collection object to perform the actual update. The method takes two arguments: the query expression and the update expression, passed in through the <code>query<\/code> and <code>update<\/code> variables. The command then saves the results returned by MongoDB to the <code>results<\/code> variable, which are then printed to the screen.<\/p>\n<p>When you run this code (along with the code base), you should receive a message indicating that one document has been updated.<\/p>\n<p>You can just as easily update multiple documents. Again, you must first define the query expression and then the update expression. This time around, however, you must use the <code>update_many<\/code> method, rather than the <code>update_one<\/code> method, as in the following example:<\/p>\n<pre class=\"lang:none theme:none\">personnel = db.get_collection(\"personnel\")\nquery = { \"dept\": \"R&amp;D\" }\nupdate = { \"$set\": { \"dept\": \"Dev\" } }\nresults = personnel.update_many(query, update)\nprint(results)<\/pre>\n<p>In this case, the command updates those documents whose <code>dept<\/code> value is <code>R&amp;D<\/code>, changing the value to <code>Dev<\/code>. The returned message should indicate that four documents were updated.<\/p>\n<h2>Deleting documents from a MongoDB database through Python<\/h2>\n<p>You can delete documents just as easily as updating them, whether one document or many. In fact, it is even easier to delete them because you don\u2019t have to specify an update expression. You need only define your query and specify the applicable collection method, as in the following example:<\/p>\n<pre class=\"lang:none theme:none\">personnel = db.get_collection(\"personnel\")\nquery = { \"_id\": 110 }\nresults = personnel.delete_one(query)\nprint(results)<\/pre>\n<p>The query expression specifies that the document\u2019s <code>_id<\/code> value must by <code>110<\/code>. The next command uses the <code>delete_one<\/code> method available to the collection object to delete the document, based on the query specified in the <code>query<\/code> variable. The results are then printed to the screen. They should indicate that one document has been deleted.<\/p>\n<p>To delete multiple documents, you must use the <code>delete_many<\/code> method rather than <code>delete_one<\/code>. For example, the following code uses the <code>delete_many<\/code> method to delete all documents with a <code>dept<\/code> value of <code>Marketing<\/code>:<\/p>\n<pre class=\"lang:none theme:none\">personnel = db.get_collection(\"personnel\")\nquery = { \"dept\": \"Marketing\" }\nresults = personnel.delete_many(query)\nprint(results)<\/pre>\n<p>The results returned by MongoDB should indicate that three documents have been deleted.<\/p>\n<p>It is possible to delete all documents in a collection by defining the query expression as an empty document (only the curly brackets), as in the following example.<\/p>\n<pre class=\"lang:none theme:none\">personnel = db.get_collection(\"personnel\")\nquery = {}\nresults = personnel.delete_many(query)\nprint(results)<\/pre>\n<p>Be extremely cautious using this approach. Wiping out an entire collection at once is seldom advisable outside a test environment.<\/p>\n<h2>Getting started with Python and MongoDB<\/h2>\n<p>Python is an extremely popular programming language that is widely used in data-driven applications that rely on MongoDB. In this article, I\u2019ve tried to give you a foundation in how to use Python to perform CRUD operations against a MongoDB collection. However, this article is only an introduction, and there is much more you can do in Python when interfacing with MongoDB collections.<\/p>\n<p>The examples are also specific to the Python language and the PyMongo driver. Although the basic principles for accessing MongoDB data are generally the same across programming languages and drivers, there are distinct differences between them, and you should refer to the documentation specific to the tools you\u2019re using. That said, I hope this article has at least provided you with a better understanding of how to access a MongoDB database from within your data-driven applications, even if you\u2019re not working with Python.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This article is a bit of a departure from the previous articles in this series. Rather than focusing exclusively on MongoDB, I explain how to access MongoDB through the Python programming language. Many data-driven applications rely on MongoDB for their data, including those written in Python, and I think it\u2019s important to understand how data&#8230;&hellip;<\/p>\n","protected":false},"author":221841,"featured_media":104153,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[53,159161],"tags":[5618,159226],"coauthors":[6779],"class_list":["post-104151","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-featured","category-mongodb","tag-mongodb","tag-mongodbseriesrobertsheldon"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/104151","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/221841"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=104151"}],"version-history":[{"count":2,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/104151\/revisions"}],"predecessor-version":[{"id":104159,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/104151\/revisions\/104159"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media\/104153"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=104151"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=104151"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=104151"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=104151"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}