Insert data to mongodb python


A document in MongoDB is the same as a record in SQL databases.

Insert Into Collection

To insert a record, or document as it is called in MongoDB, into a collection, we use the insert_one() method.

The first parameter of the insert_one() method is a dictionary containing the name(s) and value(s) of each field in the document you want to insert.

Example

Insert a record in the "customers" collection:

import pymongo

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

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

x = mycol.insert_one(mydict)

Run example »


Return the _id Field

The insert_one() method returns a InsertOneResult object, which has a property, inserted_id, that holds the id of the inserted document.

Example

Insert another record in the "customers" collection, and return the value of the _id field:

mydict = { "name": "Peter", "address": "Lowstreet 27" }

x = mycol.insert_one(mydict)

print(x.inserted_id)

Run example »

If you do not specify an _id field, then MongoDB will add one for you and assign a unique id for each document.

In the example above no _id field was specified, so MongoDB assigned a unique _id for the record (document).



Insert Multiple Documents

To insert multiple documents into a collection in MongoDB, we use the insert_many() method.

The first parameter of the insert_many() method is a list containing dictionaries with the data you want to insert:

Example

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = 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 = mycol.insert_many(mylist)

#print list of the _id values of the inserted documents:
print(x.inserted_ids)

Run example »

The insert_many() method returns a InsertManyResult object, which has a property, inserted_ids, that holds the ids of the inserted documents.


Insert Multiple Documents, with Specified IDs

If you do not want MongoDB to assign unique ids for you document, you can specify the _id field when you insert the document(s).

Remember that the values has to be unique. Two documents cannot have the same _id.

Example

import pymongo

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

mylist = [
  { "_id": 1, "name": "John", "address": "Highway 37"},
  { "_id": 2, "name": "Peter", "address": "Lowstreet 27"},
  { "_id": 3, "name": "Amy", "address": "Apple st 652"},
  { "_id": 4, "name": "Hannah", "address": "Mountain 21"},
  { "_id": 5, "name": "Michael", "address": "Valley 345"},
  { "_id": 6, "name": "Sandy", "address": "Ocean blvd 2"},
  { "_id": 7, "name": "Betty", "address": "Green Grass 1"},
  { "_id": 8, "name": "Richard", "address": "Sky st 331"},
  { "_id": 9, "name": "Susan", "address": "One way 98"},
  { "_id": 10, "name": "Vicky", "address": "Yellow Garden 2"},
  { "_id": 11, "name": "Ben", "address": "Park Lane 38"},
  { "_id": 12, "name": "William", "address": "Central st 954"},
  { "_id": 13, "name": "Chuck", "address": "Main Road 989"},
  { "_id": 14, "name": "Viola", "address": "Sideway 1633"}
]

x = mycol.insert_many(mylist)

#print list of the _id values of the inserted documents:
print(x.inserted_ids)

Run example »



Prerequisites : MongoDB Python Basics We would first understand how to insert a document/entry in a collection of a database. Then we would work on how to update an existing document in MongoDB using pymongo library in python. The update commands helps us to update the query data inserted already in MongoDB database collection.

Insert data

We would first insert data in MongoDB.

  • Step 1 – Establishing Connection: Port number Default: 27017
conn = MongoClient(‘localhost’, port-number)
  • If using default port-number i.e. 27017. Alternate connection method:
conn = MongoClient()
  • Step 2 – Create Database or Switch to Existing Database:
db = conn.dabasename
  • Create a collection or Switch to existing collection:
collection = db.collection_name
  • Step 3 – Insert : To Insert Data create a dictionary object and insert data in database. Method used to insert data:
 insert_one() or insert_many()
  • After insert to find the documents inside a collection we use find() command. The find() method issues a query to retrieve data from a collection in MongoDB. All queries in MongoDB have the scope of a single collection. Note : ‘_id’ is different for every entry in database collection. Let us understand insert of data with help on code:- 

Python3

from pymongo import MongoClient

try:

    conn = MongoClient()

    print("Connected successfully!!!")

except:  

    print("Could not connect to MongoDB")

db = conn.database

collection = db.my_gfg_collection

emp_rec1 = {

        "name":"Mr.Geek",

        "eid":24,

        "location":"delhi"

        }

emp_rec2 = {

        "name":"Mr.Shaurya",

        "eid":14,

        "location":"delhi"

        }

rec_id1 = collection.insert_one(emp_rec1)

rec_id2 = collection.insert_one(emp_rec2)

print("Data inserted with record ids",rec_id1," ",rec_id2)

cursor = collection.find()

for record in cursor:

    print(record)

  • Output:
Connected successfully!!!
Data inserted with record ids    
{'_id': ObjectId('5a02227b37b8552becf5ed2a'), 
'name': 'Mr.Geek', 'eid': 24, 'location': 'delhi'}
{'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name':
'Mr.Shaurya', 'eid': 14, 'location': 'delhi'}

Updating data in MongoDB

Methods used: update_one() and update_many() Parameters passed: + a filter document to match the documents to update + an update document to specify the modification to perform + an optional upsert parameter After inserting Data in MongoDB let’s Update the Data of employee with id:24 

Python3

from pymongo import MongoClient

try:

    conn = MongoClient()

    print("Connected successfully!!!")

except:  

    print("Could not connect to MongoDB")

db = conn.database

collection = db.my_gfg_collection

result = collection.update_many(

        {"eid":24},

        {

                "$set":{

                        "name":"Mr.Geeksforgeeks"

                        },

                "$currentDate":{"lastModified":True}

                }

        )

print("Data updated with id",result)

cursor = collection.find()

for record in cursor:

    print(record)

Output:

Connected successfully!!!
Data updated with id 
{'_id': ObjectId('5a02227b37b8552becf5ed2a'), 
'name': 'Mr.Geeksforgeeks', 'eid': 24, 'location': 
'delhi', 'lastModified': datetime.datetime(2017, 11, 7, 21, 19, 9, 698000)}
{'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name': 
'Mr.Shaurya', 'eid': 14, 'location': 'delhi'}

To find number of documents or entries in collection the are updated use.

 print(result.matched_count) 

Here output would be 1.


How do I transfer data from Python to MongoDB?

Python MongoDB Insert Document.
❮ Previous Next ❯.
Insert a record in the "customers" collection: import pymongo. ... .
Insert another record in the "customers" collection, and return the value of the _id field: mydict = { "name": "Peter", "address": "Lowstreet 27" } ... .
import pymongo. ... .
import pymongo..

How manually insert data in MongoDB?

The insert() Method To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.

How do you update a record in MongoDB using Python?

You can update a record, or document as it is called in MongoDB, by using the update_one() method. The first parameter of the update_one() method is a query object defining which document to update. Note: If the query finds more than one record, only the first occurrence is updated.

How do I import a CSV file into MongoDB using Python?

Import CSV File into MongoDB using Python.
mongoClient = MongoClient() db = mongoClient. october_mug_talk db. ... .
csvfile = open('employee.csv', 'r') reader = csv. ... .
for each in reader: row={} for field in header: row[field]=each[field].
import csv from pymongo import MongoClient mongoClient = MongoClient() db = mongoClient..