Inserting data In Mongodb via Python


Py-Mongo - Data Insertion


Demo will show how to insert one or multiple records in mongodb using python code.  Here we will use mongodb commands for insert triggered from Python

  • Insert_One: 
    • Insert only one document
  • Insert_Many: 
    • Insert multiple document


Steps:

  • Setup Mongodb and collect connection strings
  • Setup Python opne Jupyter
  • Executing Python code
  • Validate the Data in MongoDB

Step 1. 

  • Install MongoDB

Step 2. 

  • Install Python

Step 3.   

  • Execute Python Code

/*********Python Code To insert One Document******************/

#Import Librarys
import pprint
from bson.objectid import ObjectId
from pymongo import MongoClient

#Connect to MongoDB
client = MongoClient("mongodb://localhost:27017")

# Get Reference to database
db = client.algae

# Get a reference to the 'emp' collection
emp_collection = db.emp

#Prepare Data and store in the variable
new_emp = {
    "account_holder": "Linus Torvalds",
    "account_id": "MDB829001337",
    "account_type": "checking",
    "balance": 50352434
}

# Write an expression that inserts the 'new_account' document into the 'accounts' collection.
result = emp_collection.insert_one(new_emp)

# Print DocumentID inserted
document_id = result.inserted_id
print(f"_id of inserted document: {document_id}")

client.close()
/***************************/


pymongo saurabh Sinha

pymongo insert algae Services, saurabh Sinha


/*********Python Code To insert One Document******************/

#Import Librarys
import pprint
from bson.objectid import ObjectId
from pymongo import MongoClient

#Connect to MongoDB
client = MongoClient("mongodb://localhost:27017")

# Get Reference to database
db = client.algae

# Get a reference to the 'emp' collection
emp_collection = db.emp

#Prepare Data and store in the variable
new_accounts = [
    {
        "account_id": "MDB011235813",
        "account_holder": "Ada Lovelace",
        "account_type": "checking",
        "balance": 60218,
    },
    {
        "account_id": "MDB829000001",
        "account_holder": "Muhammad ibn Musa al-Khwarizmi",
        "account_type": "savings",
        "balance": 267914296,
    },
]

# Write an expression that inserts the documents 
result = emp_collection.insert_many(new_accounts)

document_ids = result.inserted_ids
print("# of documents inserted: " + str(len(document_ids)))
print(f"_ids of inserted documents: {document_ids}")

client.close()
/******************************/


pymongo insert


Step 4

  • Validate the data using Mongdb compass or from console using query
  • db.emp.find({'key':'value'})


find_one mongodb saurabh











No comments:

Post a Comment