HomeBlogWeb DevelopmentHow to Insert a Document into a MongoDB Collection

How to Insert a Document into a MongoDB Collection

16th Oct, 2023
view count loader
Read it in
6 Mins
In this article
    How to Insert a Document into a MongoDB Collection

    MongoDB is an open-source, NoSQL document database and it is a pillar of the MERN stack. It is a very useful database to work with use cases where it is difficult or impossible to predict the schema of data to be stored in the database by an application.

    MongoDB adopts a JSON-like structure to manage data, and a single such entity is called a document. To derive a similarity from the relational database world, in most cases one could consider a document in NoSQL terminology to mean the same thing as a record in a SQL DB. A group of such documents is called a collection.

    Unlike a traditional relational database, we will not require a predefined schema or table relations to store and retrieve data from a NoSQL DB like Mongo making it highly convenient and, in most scenarios, will have an edge in performance as the overhead to maintain the table relation is removed from the picture.

    Understanding NoSQL

    The term NoSQL stands for “Not only SQL” and means that we do not use tables and the relation between them for storing, organizing, and retrieving data. So, instead of rows and columns, we opt for a different approach to structure data.

    When it comes to Mongo, it takes a document-based NoSQL as discussed in the introductory passage.

    Documents and Collections in Mongo

    Like we discussed earlier, Mongo stores data in a JSON-like structure. So, a document in Mongo is a structure of field-value pairs that are used to structure, organize and store data.

    Let’s say that we have the scores of a student named “John” in two different periodic tests conducted by an institution where John is a student. We can organize this data as follows in the form of a document:

        name: "John", 
        score1: 80, 
        score2: 74 

    What we have above is a valid document in Mongo.

    Now let’s say we have ten more students, and we have ten more documents like that of John’s and we’d like to organize them so that we ensure they are co-located logically. This grouping of documents forms a collection.

    Thus, a collection is a logical group of one or more documents (in the SQL world a table would be equivalent to a collection). One or more collections form a database.

    How do I upload documents to MongoDB?
    Getting Started with MongoDB

    The MongoDB installation document which is available at https://docs.mongodb.com/manual/installation/ has step-by-step instructions to install MongoDB locally on your system for various popular operating systems. If you’d like to save all the hassle of installing things on your system and just get started working with Mongo, you could also explore the free tier of MongoDB Atlas by registering on their portal available at https://www.mongodb.com/cloud/atlas/register.

    After the installation, the Mongo daemon could be started with the following command on Linux operating systems.

    sudo systemctl start mongod

    Check the status of mongod with the following command

    sudo systemctl status mongod

    You should see the mongod services active and would be running the MongoDB server

    Retrieving data. Wait a few seconds and try to cut or copy again.
    This will vary depending on your OS and having a quick look at the installation document will help you to find it for a specific operating system.

    After the installation, run the mongo shell by typing the following command in your terminal.


    How do I upload documents to MongoDB?

    This gives us a running MongoDB instance where we could try our hands at inserting documents into a database.

    Creating a Database

    Before we create our own database on Mongo, let’s have a look at the existing ones that were created through the installation by using the following command in the mongo shell:

    show dbs

    How do I upload documents to MongoDB?
    As we can see, three databases named admin, config, and local were created by default. Now, let’s create our own database to store the documents and collections that we will be creating in this article.

    It should be interesting not that there is no explicit create command in the mongo shell to create a database. Instead, when we switch context through the “use” keyword, a new database will be created if it doesn’t exist already:

    use students

    How do I upload documents to MongoDB?

    Thus we have created a new database named students and have switched to it as well using the mongo shell.

    Create a Collection

    Let’s create a collection named `Batch2021` to store our students’ documents. We could do this by using the `createCollection` command:


    How do I upload documents to MongoDB?

    We could list the collections in a database using the following query:

    show collections

    How do I upload documents to MongoDB?

    MongoDB Insert Document

    Inserting a Single Document:

    To insert a single document into our collection we could use the method `insertOne` on our newly created collection. It is also important to note that if we don’t have a collection with a specified name mongo will create a new collection for us and insert the document into it. The collection names are case-sensitive as well.

    Let’s insert a document with the data of a student named “John” and his test scores as follows:

    db.Batch2021.insertOne({name: "John", score1: 80, score2: 75})

    How do I upload documents to MongoDB?
    As we could see from the screenshot, our single document is inserted into the collection successfully. We could also query all the documents in the collection in the following way:


    How do I upload documents to MongoDB?

    We could see a strange field named _id that we did not add in our query to insert this document. This is a special field whose value should be unique for a document in a collection. In some ways, we could think of them as primary keys in a table from a relational database paradigm.

    If we don’t pass a value (ObjectId) to this field, mongo will auto-generate this for every document as it did for us in our example. These ObjectIds have a specific length and a format that makes them valid. If you are interested in knowing more about ObjectIds, you can have a look at its documentation here: https://docs.mongodb.com/manual/reference/bson-types/#std-label-objectid.

    Inserting Multiple Documents

    We could insert multiple documents into a collection in one go using the `insertMany` operation in the mongo shell.

    Let’s insert the data of two other students into the document with inserMany:


    How do I upload documents to MongoDB?
    By default, mongo performs an ordered insert on the documents inserted using insertMany operation. This means that the documents are inserted into the document in the specific order in which we supply them to the operation. If the order doesn’t matter, we could also perform unordered insertions passing the ordered option as false.

    db.Batch2021.insertMany([{name:"Jane",score1:92,score2:87,score3:77},{name:"Adam",score1:99,score2:88}], {ordered: false})

    It is also important to note that in Mongo, the write operation is atomic only at the scope of a single document. Hence operations affecting multiple documents such as the one above or embedded documents are not atomic.

    If you are wondering what atomicity is, in simple terms, it could be defined as all or nothing. So, at a document level, it’s either that all field-value pairs get inserted or nothing gets inserted in case of a failure. But if we insert two documents through the insertMany operation and our first document is successfully inserted while the second fails. We will end up having the first document in our collection. There won’t be a rollback. Hence it is not atomic on multi-document writes.

    The Insert Method

    The insert method could be used to insert one or many documents into a collection depending on the parameter passed to it.

    db.collection.insert(<document or array of documents>, options)

    Hence, we could use it to insert a single document like this:

    db.Batch2021.insert({name: "John", score1: 80})

    Or to insert multiple documents:

    db.Batch2021.insert([{name: "Jane", score1: 94},{name:"Adam", score1:98, score2: 88}])

    The ordered and unordered inserts are performed in the same way as we discussed them in the `insertMany` section, while ordered inserts are the default approach.

    Looking to level up your coding skills? Join our Python Advanced Course and unlock the full potential of this versatile language. From data analysis to web development, Python has got you covered. Don't miss out, enroll today!

    Getting more out of MongoDB

    Thus, we have now seen how we could set up MongoDB locally and have created a database with a collection holding multiple documents which we inserted into it using the various write methods from the mongo shell.

    We have just scratched the surface of MongoDB. There are various advanced features offered by the database which you must look into, if you are considering using this database for your next project.


    Parthipan Natkunam


    Parthipan is a full-stack capable, software engineer with 7 years of industry experience, specialized in front-end engineering. Certified "AWS Developer Associate", who has worked in industries such as Ed-tech, IoT and Cyber security with companies spanning across multiple countries with varied tech stacks. Language agnostic by practice but fluent in TypeScript and JavaScript. Loves open-source and enjoys creating quality software products from scratch.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon