Python Tutorials · Python MongoDB

MongoDB Insert

Learn all about MongoDB Insert in this comprehensive tutorial.

5 min read advanced
  • To insert a record, or document as it is called in MongoDB, into a collection, we use the insert_one() method.
  • The insert_one() method returns a InsertOneResult object, which has a property, inserted_id, that holds the id of the inserted document.
  • To insert multiple documents into a collection in MongoDB, we use the insert_many() method.
  • If you do not want MongoDB to assign unique ids for your document, you can specify the _id field when you insert the document(s).

Introduction

Note: 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.

python

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.

python

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:

python

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 your 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.

python

Module quiz

2 questions
1

Which of the following is true about MongoDB Insert?

2

What is the most common pitfall when working with MongoDB Insert?

Answer all questions to submit.