Python Mongodb Insert Document
A document in MongoDB is similar to a record in an SQL table.
Insert Into Collection
To insert a document into a collection, use theinsert_one()method, whose first parameter is a dictionaryname => valuepair.
The following examplesitesinserts a document into the collection:
Example
The output after execution is:
<pymongo.results.InsertOneResult object at 0x10a34b288>
Return the _id Field
insert_one()The method returnsInsertOneResultan object, which containsinserted_idattribute, which is the inserted document'sidvalue.
Example
The output after execution is:
5b2369cac315325f3698a1cf
If we do not specify_id, MongoDB will add a uniqueid。
Insert Multiple Documents
To insert multiple documents into a collection, use theinsert_many()method, whose first parameter is a list of dictionaries.
Example
The output result is similar to the following:
[ObjectId('5b236aa9c315325f5236bbb6'), ObjectId('5b236aa9c315325f5236bbb7'), ObjectId('5b236aa9c315325f5236bbb8'), ObjectId('5b236aa9c315325f5236bbb9'), ObjectId('5b236aa9c315325f5236bbba')]
insert_many()The method returnsInsertManyResultan object, which containsinserted_idsattribute, which stores all the inserted documents'idvalues.
After executing the above search, we can check in the command terminal whether the data has been inserted:

Insert Multiple Documents with Specified _id
We can also specify the id ourselves and insert. In the following example, wesite2insert data into the collection,_idas specified by us:
Example
The output result is:
[1, 2, 3, 4, 5]
After executing the above search, we can check in the command terminal whether the data has been inserted:

Python Mongodb