Python MongoDB

What is Mongo?

Mongo is an open-source non-relational database service, written in C++. It is the ideal tool for backend services that need to save information that needs little processing quickly. These characteristics make it ideal for mobile and social networks backend services.


PyMongo is an API used for managing Mongo databases in Python. It is really easy to learn, and straightforward to use. Let’s start with the basics; the first thing you need is a database and a collection to start.
For all of the examples, the default “test” database will be used, and a collection called “People”. If you do not know how to create a collection, you can check the Mongo documentation.

Connecting to the db client

After that, you need to install PyMongo on your system. You can do it simply by using pip or adding it to your requirements.txt. In this case, as it is an example, it will be installed via pip with the following command:
python -m pip install pymongo
Then, in your project, you have to create a client to connect to the database. In order to create it, you must know the IP and port of the Mongo database. By default the Mongod port is the 27017 and, in this case, the Mongod is installed on the same computer of the Python project, so the example uses localhost as the IP address. Here you have a really simple example script:
HOST = "localhost"
PORT = "27017"

db = MongoClient("mongodb://" + HOST + ":" + PORT).test
On this script, a global “db” variable is defined as the test database on the local computer. Also, if you have user and password in your database, you can define it on the client by adding it at the beginning of the URI: user:password@mongodb://...

Populating the database

After the client is defined, we will need some data in the database to start with the API testing. You can insert data using the insert_one method from the mongo collection. For example, to add a new person to the People collection you can run the following command:
    "name": {
        "first_name": "Alice",
        "last_name": "Smith"
    "address": {
        "street": "5th Avenue",
        "building": "269",
        "coord": {"type": "Point", "coordinates": [-56.137, -34.901]}
Also if want to insert multiple documents at once, a better and more efficient way to insert data is using bulk operations. You can initialize bulk objects using the collection methods initialize_unordered_bulk_op or initialize_ordered_bulk_op. On this objects, you can insert, modify or delete data without changing the database, and then execute it to reflect those changes all at once. Here you can find an example:
bulk = db.People.initialize_unordered_bulk_op()

    # Document to be inserted


Creating queries

In PyMongo, you can define queries the same way as you do in Mongo. You can use the find method from a collection to create simple queries or the aggregate method for more complex ones. Here you have a query that returns the documents whose last names are “Smith”:
cursor = db.People.find({"name.last_name": "Smith"})
Then you can iterate over the returned documents by using:
for document in cursor:
    # Manipulation of the documents
The documents are handled as JSONs objects so you can retrieve its data using get or the brackets operators.

Updating and deleting data

In order to update, delete or replace data you should use one of the six collections methods for database modification. Those methods are the following:
  1. update_one
  2. update_many
  3. replace_one
  4. replace_many
  5. delete_one
  6. delete_many
All of them receive as their first parameter a query for the elements that will be modified. This query can use any of the operators as the find methods. As you can see on the method name, the ones ending on _one modify the first document found for that query, and the ones ending in _many change all of them.
Then, the first four methods receive as their second parameter the object to update or replace. The update methods require the $set operator, while the other can receive any JSON object.
Here you can see an example for the local database:
result = db.People.update_many({"name.last_name": "Smith"},
                                   "$set": {
                                       "name.last_name": "Johnson"
As you can see here, every person whose last name is Smith will be updated to have their last name be Johnson instead.
Also, the replace methods can receive an optional parameter named upsert. When this value is true, if no document was found by the query, then it inserts the object. By default this value is false.

Creating and using indexes

Indexes are used to improve the speed of queries, or for special kind of queries, like geospatial queries. Creating indexes is really simple. You have to use the create_index collection method, which receives a list of all the indexes you want to create.
The indexes are maps of values, where the key is the name of the attribute and the value the kind of index which will be created. The index can be any of the listed here:
  3. GEO2D (“2d” - 2-dimensional geospatial index)
  4. GEOSPHERE (“2dsphere” - spherical geospatial index)
  6. TEXT
Here you have an example that creates a spherical index and then makes a geospatial query:
    ("address.coord", GEOSPHERE)

longitude = -56.134
latitude = -34.9

distance = 304.8  # 1000ft in mts

cursor = db.People.aggregate([{
    "$geoNear": {
        "near": {"type": "Point", "coordinates": [longitude, latitude]},
        "spherical": True,
        "distanceField": "distance",
        "maxDistance": distance
The first command creates the geospatial index by the address.coord attribute, then it creates a query that finds the people that are within 1000ft of the defined position.
Congratulations! Now you know how to manipulate Mongo databases with Python. If you want to see a sample project you can check ours here.


  1. I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.
    It’s great to come across a blog every once in a while that isn’t the same out of date rehashed material. Fantastic read.

    Python Training in Chennai | Python Training Institutes in Chennai

    1. Thank you Mari for your words. You can follow us in Linkedin and Twitter to find out when we have new posts on the blog. I'll share the links right here:

  2. Pretty blog, so many ideas in a single site, thanks for the informative articlesoftware testing course in Chennai

  3. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.
    Python Training in Bangalore


  4. Thanks for sharing this post. Your post is really very helpful its students.

    python training in chennai

    selenium training in chennai

  5. Bored of sitting at home? Play casino and get paid for it perfect popular online casinos Play and win.

  6. This comment has been removed by the author.

  7. Если вам нужны профили для светодиодных лент то я обычно беру их у компании Ekodio, быстрая доставка и супер сервис

  8. today damn all day stay on this site fancy online gambling games for real money There are so many cool game machines and all sorts of other gambling games I will say one thing to have fun here

  9. superb blog
    Apponix Technologies

  10. Attend The Best Python Training in Bangalore From ExcelR. Practical Python Training in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Best Python Training in Bangalore.

  11. Attend The Data Analytics Courses in Bangalore From ExcelR. Practical Data Analytics Courses in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analytics Courses in Bangalore.
    ExcelR Data Analytics Courses in Bangalore

  12. Great Article. It was so informative. Always try to share this type of informative article. Keep it up!! Machine Learning Course Bangalore

  13. This comment has been removed by the author.

  14. I learned World's Trending Technology from certified experts for free of cost. I Got a job in decent Top

    MNC Company with handsome 14 LPA salary, I have learned the World's Trending Technology from Data science training in btm

    experts who know advanced concepts which can help to solve any type of Real-time issues in

    the field of Python. Really worth trying Freelance seo expert in



  15. Thanks for sharing.Really Wonderful article with great piece of information and well written
    AWS training institute in Bangalore

  16. Thank you for excellent article.Great information for new guy like antimalware service executable

  17. Which are the top alternative for receiving the support to resolve Coincorner account issues? Frankly speaking, there are a variety of ways to reach the Coincorner experts and obtain support from them. you desire to get the immediate technical support, the Coincorner helpdesk number would prove to be the most excellent alternative. The Coincorner support executives not only remain active around the clock to render quick assistance, but at the same time, they are also very well versed in resolving the issues. They keep the solution of all Coincorner issues at their finger tips. They will provide instant technical support without as and when you dial the Coincorner phone number.

  18. This was not just great in fact this was really perfect your talent in writing was great. ExcelR Machine Learning Course In Pune

  19. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
    Data Science Institute in Bangalore

  20. Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more.
    Data Science Certification in Bangalore

  21. This is an excellent post I seen thanks to share it. It is really what I wanted to see hope in future you will continue for sharing such a excellent post.
    Data Science Course in Bangalore

  22. If you don"t mind proceed with this extraordinary work and I anticipate a greater amount of your magnificent blog entries
    Data Science Training in Bangalore

  23. Such a very useful article. Very interesting to read this article. I would like to thank you for the efforts you had made for writing this awesome article.
    Data Science Course in Pune
    Data Science Training in Pune

  24. Attend The Data Analyst Course From ExcelR. Practical Data Analyst Course Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analyst Course.
    Data Analyst Course

  25. Thumbs up guys your doing a really good job. It is the intent to provide valuable information and best practices, including an understanding of the regulatory process.
    Cyber Security Course in Bangalore

  26. Very nice blog and articles. I am really very happy to visit your blog. Now I am found which I actually want. I check your blog everyday and try to learn something from your blog. Thank you and waiting for your new post.
    Cyber Security Training in Bangalore

  27. I am impressed by the information that you have on this blog. Thanks for Sharing
    Ethical Hacking in Bangalore

  28. Cool stuff you have and you keep overhaul every one of us.

    Data Science Course

  29. Thanks for the informative and helpful post, obviously in your blog everything is good..

    Data Science Training

  30. Attend The Business Analytics Courses From ExcelR. Practical Business Analytics Courses Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analytics Courses.
    Business Analytics Courses

  31. Very interesting blog. A lot of the blogs I see these days don't provide anything that interests me, but I'm really interested in this one. I just thought I would post and let you know.

    Data Science Courses

  32. This article is good enough for someone to understand this amazing thing, and I'm sure everyone will appreciate these cool things.

    Data Science Certification

  33. This is my first time visit here. From the tons of comments ExcelR Machine Learning Courses on your articles.I guess I am not only one having all the enjoyment right here!

  34. I'm highly dazed with the quality of the content which you have penned down. This is a splendid article! Your article has all the necessary information on the respective topic.

    SAP training in Kolkata
    SAP training Kolkata
    Best SAP training in Kolkata
    SAP course in Kolkata

  35. Extraordinary blog went amazed with the content they have developed in a very descriptive manner. Hope you deliver the same near the future as well. Gratitude to the blogger for the efforts.

    360DigiTMG Cloud Computing Course

  36. Terrific post thoroughly enjoyed reading the blog and more over found to be the tremendous one. Infact, educating the participants with it's amazing content. Hope you share the similar content consecutively.

    360DigiTMG Data Science Course

  37. I have really enjoyed reading your blog, it is filled with valuable information thanks for sharing.
    typeerror nonetype object is not subscriptable

  38. It is always so interesting to visit your site. What a great information, thanks for sharing. it will help me a lot in my learning.

    360 DigiTMG Business Analytics Course in Bangalore

  39. I like to see websites that include the price of free shipping from the excellent helpful resource. I really enjoyed reading your post. Thank you!

    360DigiTMG Data Analytics Course in Bangalore

  40. Fantastic blog with unique content and information provided was very valuable waiting for next blog update thank you .
    Ethical Hacking Course in Bangalore 360DigiTMG

  41. Really fine and interesting informative article. I used to be looking for this kind of advice and enjoyed looking over this one. typeerror nonetype object is not subscriptable

  42. Terrific post thoroughly enjoyed reading the blog and more over found to be the tremendous one. In fact, educating the participants with it's amazing content. Hope you share the similar content consecutively.

    artificial intelligence course in bhilai

  43. Honestly speaking this blog is absolutely amazing in learning the subject that is building up the knowledge of every individual and enlarging to develop the skills which can be applied in to practical one. Finally, thanking the blogger to launch more further too.

    Data Science training in Bhilai

  44. Stupendous blog huge applause to the blogger and hoping you to come up with such an extraordinary content in future. Surely, this post will inspire many aspirants who are very keen in gaining the knowledge. Expecting many more contents with lot more curiosity further.

    Digital Marketing Course in Bhilai

  45. Top quality blog with very informative information found very useful thanks for sharing.
    Data Science Course in Hyderabad 360DigiTMG

  46. I am highly overwhelmed to read this perfect piece of writing. It has really enthused me to read more on this topic.
    Data Science training in Mumbai
    Data Science course in Mumbai
    SAP training in Mumbai

  47. I will very much appreciate the writer's choice for choosing this excellent article suitable for my topic. Here is a detailed description of the topic of the article that helped me the most.
    unindent does not match any outer indentation level

  48. I'm glad I found this blog! Occasionally, students want to know the keys to writing productive literary essays. Your first-class knowledge of this great job can become a suitable foundation for these people. Good
    unindent does not match any outer indentation level python


  49. Awesome article with top quality information and I appreciate the writer's choice for choosing this excellent topic found valuable thank you.
    Data Science Training in Hyderabad


  50. Amazing article with informative information found valuable and enjoyed reading it thanks for sharing.
    Data Analytics Course Online

  51. Really, this article is truly one of the best, information shared was valuable and resourceful Very good work thank you.
    Data Scientist Training in Hyderabad

  52. I really appreciate this wonderful message you have given us. I assure you that would be beneficial for most people. PMP Certification in Hyderabad

  53. Very well written post. Thanks for sharing this, I really appreciate you taking the time to share with everyone. Pmp Training Hyderabad


Post a Comment