Get startedGet started for free

Inserting documents

1. Inserting documents

So far, you've learned how to find and filter data in MongoDB. Now it's time to shift gears, from reading data to writing it. In this lesson, you’ll learn how to insert new documents into a collection, both one at a time, and in bulk.

2. Why insert data?

Before you can query or analyze data, it has to exist in your database. That means you need a way to add it too! We'll cover two ways to do this: insert_one() to add a single document, and insert_many() when you have several to add at once.

3. Inserting a single document

Let’s start with insert_one(). Before the insert, we can check how many documents are in the collection using count_documents({}). Let's next define our new document, written as a regular Python dictionary— where each key is a field name, and each value is the data you want to store. Then, we call insert_one() to add the new movie. MongoDB automatically assigns a unique _id, and returns it in the inserted_id attribute. Finally, we check the document count again—confirming that the collection now holds one more document.

4. Inserting multiple documents

Want to insert several documents at once? Use insert_many(). Instead of a single dictionary, you pass in a list of dictionaries. Each one will be added as its own document in the collection. This is especially useful when importing a batch of record, like movies from a dataset or user entries from a form. Just like insert_one(), MongoDB will return the auto-generated unique _id values for each new document.

5. Let's practice!

Use insert_one() when you're adding a single document, use insert_many() when you've got a batch ready to go. Time for some exercises.

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.