Python – MongoDB – Insert

Python - MongoDB - Insert

MongoDB saves data in BSON (binary JSON) format, which makes it easy for MongoDB to share data with other programming languages. MongoDB is often preferred over traditional SQL databases for its ease of use and greater flexibility. Python is a high-level programming language, which is widely popular due to its dynamic semantics and readability. Using Python with MongoDB allows developers to create high-quality, scalable web applications that can handle large volumes of data with ease.

Before you Start

Before you get started with Python and MongoDB, you will need to download and install several pieces of software. Please follow these steps to set up your environment:

  1. Download and install the latest version of Python from www.python.org/downloads/
  2. Install the Python package manager, pip by following the instructions at pip.pypa.io/en/stable/installing/
  3. Download and install MongoDB community server for your operating system from www.mongodb.com/download-center/community
  4. Install the PyMongo library using pip by running the following command in your command prompt or terminal:
pip install pymongo

PyMongo is a Python library that provides tools for interacting with MongoDB.

Connecting to MongoDB from Python

The first thing you need to do is connect to your MongoDB database from your Python script. Here is an example:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]

This script creates a new client that connects to your MongoDB server at localhost:27017. Next, it selects the mydatabase database for use.

Inserting a Single Record

Inserting a single record into MongoDB is straightforward in Python. Here is an example:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycollection = mydb["customers"]

mydict = { "name": "John", "address": "Highway 37" }

x = mycollection.insert_one(mydict)

print(x.inserted_id)

The above code sample creates a new collection called customers in mydatabase. We then create a dictionary object that we want to insert into the customers collection. Finally, the insert_one() method is called on the collection object with the dictionary object as its argument. The method returns an InsertOneResult object, which includes the _id of the newly inserted document. This ID can be used to query for the document later if needed.

Here is the output of the above code block:

60c64ab16817b013c1d4b4af

The output shows the ID of the newly inserted document.

Inserting Multiple Records

Inserting multiple records into MongoDB is also quite simple. Here is an example:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycollection = mydb["customers"]

mylist = [
  { "name": "Amy", "address": "Apple st 652" },
  { "name": "Hannah", "address": "Mountain 21" },
  { "name": "Michael", "address": "Valley 345" },
  { "name": "Sandy", "address": "Ocean blvd 2" },
  { "name": "Betty", "address": "Green Grass 1" },
  { "name": "Richard", "address": "Sky st 331" },
  { "name": "Susan", "address": "One way 98" },
  { "name": "Vicky", "address": "Yellow Garden 2" },
  { "name": "Ben", "address": "Park Lane 38" },
  { "name": "William", "address": "Central st 954" },
  { "name": "Chuck", "address": "Main Road 989" },
  { "name": "Viola", "address": "Sideway 1633" }
]

x = mycollection.insert_many(mylist)

print(x.inserted_ids)

The above code sample creates a new collection called customers in mydatabase. We then create a list of dictionary objects that we want to insert into the customers collection. Finally, the insert_many() method is called on the collection object with the list object as its argument. The method returns an InsertManyResult object, which includes a list of the _id of each newly inserted document. This list can be used to query for the documents later if needed.

Here is the output of the above code block:

[ObjectId('60c64d0e6817b013c1d4b4b0'), ObjectId('60c64d0e6817b013c1d4b4b1'), ObjectId('60c64d0e6817b013c1d4b4b2'), ObjectId('60c64d0e6817b013c1d4b4b3'), ObjectId('60c64d0e6817b013c1d4b4b4'), ObjectId('60c64d0e6817b013c1d4b4b5'), ObjectId('60c64d0e6817b0... 

The output shows the IDs of the newly inserted documents.

Conclusion

In this tutorial, we covered the basics of inserting records into MongoDB from Python. We looked at how to insert a single record and how to insert multiple records. We hope this article helps you get started with Python and MongoDB.

Leave a Reply

Your email address will not be published. Required fields are marked *