All Courses

Python MongoDB - Insert Document

Neha Kumawat

9 months ago

Python MongoDB | insideAIML
Table of Content
  • Introduction
  • Creating a Collection Using Python

Introduction

          In this article we will try to see how we can insert documents into MongoDB using Python. You can save documents in MongoDB using the insert () method. This method accepts a JSON document as a parameter.
In MongoDB, the insert () method inserts one or more documents into the collection. It takes two parameters, the first parameter is the document or document array we want to insert and the rest is optional.  
Syntax
db.collection.insert()
Inserts a document or documents into a collection.
The insert() method has the following syntax:
db.collection.insert(   
<document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)
Parameter              Type                             Description
document             document or array     A document or array of documents to insert into the collection.
writeConcern       document                   Optional. A document expressing the write concern. Omit to use the                                                                                    default write concern. 
ordered                boolean                       Optional. If true, perform an ordered insert of the documents in the                                                                                 array, and if an error occurs with one of documents, MongoDB will                                                                                    return without processing the remaining documents in the array.   
                                                                 If false, perform an unordered insert, and if an error occurs with one of                                                                                 documents, continue processing the remaining documents in the array.
                                                                 Defaults to true.
The insert() returns an object that contains the status of the operation.
Returns:
  • A WriteResult object for single inserts.
  • A BulkWriteResult object for bulk inserts.
Example

> use mydatabase
switched to db mydatabase
> db.createCollection("Demo")
{ "ok" : 1 }
> document = {"name": "Sham", "age": "25", "city": "Pune"}
{ "name": "Sahm", "age": "25", "city": "Pune" }
> db.sample.insert(document)
WriteResult({ "nInserted" : 1 })
>
Similarly, you can also insert multiple documents using the insert() method.
 use demoDB
switched to db demoDB
> db.createCollection("demo")
{ "ok" : 1 }
> data = [
   {"_id": "1", "name": "Amar", "age": "21", "city": "Pune"}, 
   {"_id": "2", "name" : "Akbar", "age" : 23, "city" : "Hydrabad" }, 
   {"_id": "3", "name" : "Anthani", "age" : 25, "city" : "Mumbai" }
]
[
   {"_id": "1", "name": "Amar", "age": "21", "city": "Pune"}, 
   {"_id": "2", "name" : "Akbar", "age" : 23, "city" : "Hydrabad" }, 
   {"_id": "3", "name" : "Anthani", "age" : 25, "city" : "Mumbai" }
]
> db.demo.insert(data)
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 3,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})
>

Creating a Collection Using Python

          Pymongo provides a method named insert_one() to insert a document in MangoDB. To this method, we need to pass the document in dictionary format.
Example
Following example inserts a document in the collection named example.

from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['mydb']

#Creating a collection
coll = db['example']

#Inserting document into a collection
doc1 = {"name": "Ram", "age": "26", "city": "Hyderabad"}
coll.insert_one(doc1)
print(coll.find_one())
Output:

{'_id': ObjectId('5d63ac6ce043e2a93775858b'), 'name': 'Sham', 'age': '25', 'city': 'Pune'}
To insert multiple documents into MongoDB using pymongo, you need to invoke the insert_many() method.

from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['mydb']

#Creating a collection
coll = db['example']

#Inserting document into a collection
data = [
   {"_id": "1", "name": "Amar", "age": "21", "city": "Pune"}, 
   {"_id": "2", "name" : "Akbar", "age" : 23, "city" : "Hydrabad" }, 
   {"_id": "3", "name" : "Anthani", "age" : 25, "city" : "Mumbai" }
]
res = coll.insert_many(data)
print("Data inserted ......")
print(res.inserted_ids)
Output:
Data inserted ......
['1', '2', '3']
I hope you enjoyed reading this article and finally, you came to know about Python MongoDB - Insert Document.
For more such blogs/courses on data science, machine learning, artificial intelligence and emerging new technologies do visit us at InsideAIML.
Thanks for reading…
Happy Learning…

Submit Review