Python Mongodb Insert Document
# Python3.x Python MongoDB Insert Document
[ Python MongoDB](#)
A document in MongoDB is similar to a record in an SQL table.
### Insert into Collection
To insert a document into a collection, use the `insert_one()` method. The first parameter of this method is a dictionary of `name => value` pairs.
The following example inserts a document into the **sites** collection:
## Example
#!/usr/bin/python3 import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")mydb = myclientmycol = mydbmydict = { "name": "TUTORIAL", "alexa": "10000", "url": "" } x = mycol.insert_one(mydict)print(x)print(x)
The output of the execution is:
### Return the _id Field
The `insert_one()` method returns an **InsertOneResult** object, which contains the **inserted_id** property, which is the **id** value of the inserted document.
## Example
#!/usr/bin/python3 import pymongo myclient = pymongo.MongoClient('mongodb://localhost:27017/')mydb = myclient['tutorialdb']mycol = mydbmydict = { "name": "Google", "alexa": "1", "url": "https://www.google.com" } x = mycol.insert_one(mydict)print(x.inserted_id)
The output of the execution is:
5b2369cac315325f3698a1cf
If we do not specify the **_id** when inserting a document, MongoDB will add a unique **id** to each document.
### Insert Multiple Documents
To insert multiple documents into a collection, use the `insert_many()` method. The first parameter of this method is a list of dictionaries.
## Example
#!/usr/bin/python3 import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")mydb = myclientmycol = mydbmylist = [ { "name": "Taobao", "alexa": "100", "url": "https://www.taobao.com" }, { "name": "QQ", "alexa": "101", "url": "https://www.qq.com" }, { "name": "Facebook", "alexa": "10", "url": "https://www.facebook.com" }, { "name": "Zhihu", "alexa": "103", "url": "https://www.zhihu.com" }, { "name": "Github", "alexa": "109", "url": "https://www.github.com" } ]x = mycol.insert_many(mylist)# Print the _id values of all inserted documents print(x.inserted_ids)
The output is similar to the following:
[ObjectId('5b236aa9c315325f5236bbb6'), ObjectId('5b236aa9c315325f5236bbb7'), ObjectId('5b236aa9c315325f5236bbb8'), ObjectId('5b236aa9c315325f5236bbb9'), ObjectId('5b236aa9c315325f5236bbba')]
The `insert_many()` method returns an **InsertManyResult** object, which contains the **inserted_ids** property, which holds the **id** values of all inserted documents.
After completing the above insertion, we can check if the data has been inserted in the command terminal:
!(#)
### Insert Multiple Documents with Specified _id
YouTip