Insert Data into MongoDB

Deployment Type:
Client:

    Author: MongoDB Documentation Team

    In this guide, you will insert data into MongoDB.

    Time required: 15 minutes

    What You’ll Need

    Warning

    If you are running MongoDB locally and have not enabled authentication, your MongoDB instance is not secure.

    Check Your Environment

    You will need to ensure that your MongoDB instance is running and accessible.

    Check that you have an Atlas account and have deployed a MongoDB database cluster. See Create an Atlas Account and Cluster for information on how to login and create a cluster in Atlas.

    To make sure that your MongoDB instance is running on Windows, run the following command from the Windows command prompt:

    tasklist /FI "IMAGENAME eq mongod.exe"
    

    If a mongod.exe instance is running, you will see something like:

    Image Name                     PID Session Name        Session#    Mem Usage
    ========================= ======== ================ =========== ============
    mongod.exe                    8716 Console                    1      9,508 K
    

    To make sure your MongoDB instance is running on Mac, run the following command from your terminal:

    ps -e | grep 'mongod'
    

    If a mongod instance is running, you will see something like:

    89780 ttys026    0:53.48 ./mongod
    

    To make sure your MongoDB instance is running on Linux, run the following command from your terminal:

    ps -e| grep 'mongod'
    

    If a mongod instance is running, you will see something like:

    89780 ttys026    0:53.48 ./mongod
    

    Procedure

    1

    Connect to Your MongoDB Instance

    Select the operating system platform on which you are running the MongoDB client you have selected.

    Pass the URI to the mongo shell followed by the --password option. You will then be prompted for your password.

    mongo.exe <URISTRING_SHELL_NOUSER>
    

    Pass the URI to the mongo shell followed by the --password option. You will then be prompted for your password.

    mongo <URISTRING_SHELL_NOUSER>
    

    Pass the URI to the mongo shell followed by the --password option. You will then be prompted for your password.

    mongo <URISTRING_SHELL_NOUSER>
    

    If you wish to manually configure your Compass connection, load Compass and select the New Connection link. You will see a form where you can enter connection information for MongoDB.

    Atlas users can copy a URI string from the Atlas console into Compass. MongoDB Compass can detect whether you have a MongoDB URI connection string in your system clipboard and auto- populate the connection dialog from the URI.

    See Set Up Atlas Connectivity for information on how to get the Atlas connection string URI into your copy buffer.

    If Compass was already running when you copied the URI string, click the NEW CONNECTION button.

    ../../_images/connect-to-host.png

    You will be prompted to populate the connection dialog. Click Yes.

    You should then populate the password field with the proper password for your MongoDB user in the connection form.

    Note

    Errors related to connecting through Compass will appear in red at the top of the Connect screen.

    It’s a good idea to put your connection code in a class so that it can be reused.

    from pymongo import MongoClient
    
    class Connect(object):
        @staticmethod    
        def get_connection():
            return MongoClient("<URISTRING>")
    

    If your connection_string starts with mongodb+srv, you need to install the dnspython module with

    python -m pip install dnspython
    

    Now add code to call the class you just created.

    from connect import Connect
    from pymongo import MongoClient
    
    connection = Connect.get_connection()
    
        final String uriString = "<URISTRING>";
        MongoClientURI uri = new MongoClientURI(uriString);
        MongoClient mongoClient = new MongoClient(uri);
    
    const MongoClient = require('mongodb').MongoClient;
    const assert = require('assert');
    
    // Connection URL
    const url = '<URISTRING>';
    
    // Use connect method to connect to the Server
    MongoClient.connect(url, function(err, client) {
      assert.equal(null, err);
      client.close();
    });
    

    The asyncio and pprint imports will be used as you add functionality to your example code.

    import motor.motor_asyncio
    import asyncio
    import pprint
    
    client = motor.motor_asyncio.AsyncIOMotorClient('<URISTRING>')
    

    The MongoDB.Bson package is used in CRUD operations, so you’ll import it here.

    using System;
    using MongoDB.Bson;
    using MongoDB.Driver;
    
    namespace csharptest
    {
        class Connect
        {
            static void Main(string[] args)
            {
               var client = new MongoClient("<URISTRING>");
            }
        }
    }
    
    2

    Switch to the test Database

    To switch to the test database in the mongo shell, type

    use test
    

    If the database has not been created already, click the Create Database button.

    Screeenshot after connecting with the "Create Database" button.

    Select the test database on the left side of the Compass interface. Compass will list all of the collections in the database below the database name.

    Screenshot of the MongoDB Compass UI showing with the "test" database selected in the list of databases in the cluster.

    To access the test database:

    db = client.test
    

    Switch to the test database and access the inventory collection.

    MongoDatabase mongoDB = mongoClient.getDatabase("test");
    MongoCollection<Document> collection = mongoDB.getCollection("inventory");
    

    Within the connect block, set db to the test database.

    const db = client.db("test");
    

    To access the test database:

    db = client.test
    

    Switch to the test database and access the inventory collection.

    var database = client.GetDatabase("test");
    var collection = database.GetCollection<BsonDocument>("inventory");
    
    3

    Insert a Single Document

    Now you are ready to create your first document in MongoDB.

    MongoDB stores documents as BSON, a binary form of JavaScript Object Notation JSON. The documents are stored in collections.

    The following example inserts a new document into the inventory collection. If the document does not specify an _id field, MongoDB adds the _id field with an ObjectId value to the new document.

    To insert a single document using MongoDB Compass:

    1. Navigate to the collection you wish to insert the document into:

      1. In the left-hand MongoDB Compass navigation pane, click the database to which your target collection belongs.
      2. From the database view, click the target collection name.
    2. Click the Insert Document button:

      ../../_images/compass-insert-button.png
    3. For each field in the document, select the field type and fill in the field name and value. Add fields by clicking the last line number, then clicking Add Field After …

      • For Object types, add nested fields by clicking the last field’s number and selecting Add Field After …
      • For Array types, add additional elements to the array by clicking the last element’s line number and selecting Add Array Element After …
    4. Once all fields have been filled out, click Insert.

    The following example inserts a new document into the test.inventory collection:

    The following example inserts a new document into the inventory collection. If the document does not specify an _id field, the PyMongo driver adds the _id field with an ObjectId value to the new document. See Insert Behavior.

    The following example inserts a new document into the inventory collection. If the document does not specify an _id field, the driver adds the _id field with an ObjectId value to the new document. See Insert Behavior.

    First, get the inventory collection.

        MongoDatabase db = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = db
                .getCollection("inventory");
    

    The following example inserts a new document into the inventory collection. If the document does not specify an _id field, the Node.js driver adds the _id field with an ObjectId value to the new document. See Insert Behavior.

    The following example shows the api call required to insert a new document into the inventory collection. If the document does not specify an _id field, the Motor driver adds the _id field with an ObjectId value to the new document. See Insert Behavior.

    The following example inserts a new document into the inventory collection. If the document does not specify an _id field, the C# driver adds the _id field with an ObjectId value to the new document. See Insert Behavior.

    db.inventory.insertOne(
       { "item" : "canvas",
         "qty" : 100,
         "tags" : ["cotton"],
         "size" : { "h" : 28, "w" : 35.5, "uom" : "cm" }
       }
    )
    
    ../../_images/compass-insert-document-inventory.png
    db.inventory.insert_one(
        {"item": "canvas",
         "qty": 100,
         "tags": ["cotton"],
         "size": {"h": 28, "w": 35.5, "uom": "cm"}})
    

    Next, populate a Document with fields and an embedded document, and insert it into the database.

    Document canvas = new Document("item", "canvas")
            .append("qty", 100)
            .append("tags", singletonList("cotton"));
    
    Document size = new Document("h", 28)
            .append("w", 35.5)
            .append("uom", "cm");
    canvas.put("size", size);
    
    collection.insertOne(canvas);
    
    db.collection('inventory').insertOne({
      item: "canvas",
      qty: 100,
      tags: ["cotton"],
      size: { h: 28, w: 35.5, uom: "cm" }
    })
    .then(function(result) {
      // process result
    })
    
    await db.inventory.insert_one(
        {"item": "canvas",
         "qty": 100,
         "tags": ["cotton"],
         "size": {"h": 28, "w": 35.5, "uom": "cm"}})
    

    For completeness, this is how you might wrap this call and run it with the asyncio event loop.

    Run the loop:

    async def do_insert_one():
        document = await db.inventory.insert_one(
            {"item": "canvas",
             "qty": 100,
             "tags": ["cotton"],
             "size": {"h": 28, "w": 35.5, "uom": "cm"}})
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(do_insert_one())
    
    var document = new BsonDocument
    {
        { "item", "canvas" },
        { "qty", 100 },
        { "tags", new BsonArray { "cotton" } },
        { "size", new BsonDocument { { "h", 28 }, { "w", 35.5 }, { "uom", "cm" } } }
    };
    collection.InsertOne(document);
    

    Unlike SQL tables, MongoDB collections have dynamic schemas. That is, a single collection can store documents that differ in shapes (i.e. contain different fields and value types). And unlike SQL, no DDL operation is required to add or remove fields or modify field types. You just update the documents directly.

    Note

    While MongoDB does support dynamic collection definitions, you can also enforce a uniform schema for the documents in your collection. See JSON Schema validation.

    When you are done working with your MongoDB data, close your connection to MongoDB:

    mongoClient.close();
    

    Summary

    If you have successfully completed this guide, you have created your first MongoDB data. In the next guide, you will check your work by retrieving the information you just saved.

    What’s Next

    In this guide, you will read all documents from a collection in the MongoDB database.