Navigation

Insert and View Data in Your Cluster

Insert and View Data

Estimated completion time: 5 minutes

The following steps in this tutorial show you how to insert and interact with data on your cluster. Select the appropriate tab based on how you would like to interact with your cluster data:

Drivers allow you to interact with your databases programmatically using one of several available programming languages. For a complete list of MongoDB drivers, see the driver documentation.

    Insert Data into your Atlas Cluster with the PyMongo Driver

    Estimated completion time: 5 minutes

    In the previous section you used the PyMongo driver to connect to your Atlas cluster. In this section you’ll create a new collection, add data to it, and read the new data.

    1

    Create a new database on your cluster.

    We have already established our client connection and stored it in a variable called client. Run the following command in your Python shell to create a database on your cluster:

    db = client.gettingStarted
    

    This command creates a new database on your cluster called gettingStarted. The variable db points to your new database.

    2

    Create a collection for your database.

    Run the following command in your Python shell to create a new collection for your database:

    people = db.people
    

    This command creates a new collection in your gettingStarted database called people. The variable people points to your new collection.

    3

    Create a new document to insert into your collection.

    In your Python shell, run the following command to create a document which will be inserted into your collection:

    import datetime
    personDocument = {
      "name": { "first": "Alan", "last": "Turing" },
      "birth": datetime.datetime(1912, 6, 23),
      "death": datetime.datetime(1954, 6, 7),
      "contribs": [ "Turing machine", "Turing test", "Turingery" ],
      "views": 1250000
    }
    

    The document is stored in a variable called personDocument.

    Note

    This command does not insert the document into your collection. This command only specifies the document. We will insert the document in the next step.

    4

    Insert the document into your collection.

    In your Python shell, run the following command to insert the document you created in the previous step into your collection:

    people.insert_one(personDocument)
    

    Remember that the people variable refers to our people collection we specified in a previous step of this section, and personDocument contains the document we want to insert.

    If your insert was successful, PyMongo displays a message similar to the following:

    <pymongo.results.InsertOneResult object at 0x10950e5f0>
    

    View Your Cluster Data

    Now that you have successfully inserted a document into your Atlas cluster using the PyMongo driver, you can try reading that data with the PyMongo find_one() method.

    The following command returns one document from the people collection that has a name.last value of Turing:

    people.find_one({ "name.last": "Turing" })
    

    This command returns the following output. This example has been broken into multiple lines for readability.

    {
      '_id': ObjectId('5ecd43aa2600f51da704b35f'),
      'name': {
        'first': 'Alan',
        'last': 'Turing'
      },
      'birth': datetime.datetime(1912, 6, 23, 0, 0),
      'death': datetime.datetime(1954, 6, 7, 0, 0),
      'contribs': [
        'Turing machine',
        'Turing test',
        'Turingery'
      ],
      'views': 1250000
    }
    

    Note

    You may see a different value for ObjectId, because it is a system-generated value.

    See also

    For more information on querying data with PyMongo, see the PyMongo documentation.

    Summary

    Congratulations! You’ve used the PyMongo driver to interact with data on your cluster.

    Insert Data into your Atlas Cluster with the Node.js Driver

    Estimated completion time: 5 minutes

    In the previous section you used the Node.js driver to connect to to your Atlas cluster. In this section you’ll create a new collection, add data to it, and read the new data.

    The following sample application adds a document to a collection called people in the test database. To try it out, copy the following code into a file called insert-data.js.

    Note

    Replace the placeholders on line 4 with your Atlas connection string.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    const { MongoClient } = require("mongodb");
     
    // Replace the following with your Atlas connection string                                                                                                                                        
    const url = "mongodb+srv://<username>:<password>@clustername.mongodb.net/test?retryWrites=true&w=majority&useNewUrlParser=true&useUnifiedTopology=true";
    const client = new MongoClient(url);
     
     // The database to use
     const dbName = "test";
                          
     async function run() {
        try {
             await client.connect();
             console.log("Connected correctly to server");
             const db = client.db(dbName);
    
             // Use the collection "people"
             const col = db.collection("people");
    
             // Construct a document                                                                                                                                                              
             let personDocument = {
                 "name": { "first": "Alan", "last": "Turing" },
                 "birth": new Date(1912, 5, 23), // June 23, 1912                                                                                                                                 
                 "death": new Date(1954, 5, 7),  // June 7, 1954                                                                                                                                  
                 "contribs": [ "Turing machine", "Turing test", "Turingery" ],
                 "views": 1250000
             }
    
             // Insert a single document, wait for promise so we can read it back
             const p = await col.insertOne(personDocument);
             // Find one document
             const myDoc = await col.findOne();
             // Print to the console
             console.log(myDoc);
    
            } catch (err) {
             console.log(err.stack);
         }
     
         finally {
            await client.close();
        }
    }
    
    run().catch(console.dir);
    

    To run the sample application, use the following command:

    node insert-data.js
    

    See also

    For more information on querying data with Node.js, see the Node.js documentation.

    Summary

    Congratulations! You’ve used the Node.js driver to interact with data on your cluster.

    Insert Data Into Your Cluster Using the Shell

    Estimated completion time: 1 minute

    Now that you have successfully connected to your Atlas cluster using the mongo shell, let’s insert a document into your cluster.

    1

    Switch to a new database called gettingStarted.

    In the mongo, run the following command:

    use gettingStarted
    

    This command creates a new database called gettingStarted and points your mongo shell environment to that database.

    2

    Insert a document into your database.

    In the mongo shell, run the following command to insert a document into your new database:

    db.people.insert({
      name: { first: "Alan", last: "Turing" },
      birth: new Date('Jun 23, 1912'),
      death: new Date('Jun 07, 1954'),
      contribs: [ "Turing machine", "Turing test", "Turingery" ],
      views : NumberLong(1250000)
    })
    

    This command creates a new collection in your gettingStarted database called people and inserts one document into that collection.

    You should see the following output, confirming that you have successfully inserted a document into your collection:

    WriteResult({ "nInserted" : 1 })
    

    View Data Using the Shell

    Estimated completion time: 1 minute

    Now we can try reading the data we just inserted into our cluster.

    The following command searches our people collection for documents which have a name.last value of Turing:

    db.people.find({ "name.last": "Turing" })
    

    When you run this command, you should see the following output:

    {
      "_id" : ObjectId("5c9bca3c5345268c98ac7abc"),
      "name" : {
        "first" : "Alan",
        "last" : "Turing"
      },
      "birth" : ISODate("1912-06-23T04:00:00Z"),
      "death" : ISODate("1954-06-07T04:00:00Z"),
      "contribs" : [
        "Turing machine",
        "Turing test",
        "Turingery"
      ],
      "views" : NumberLong(1250000)
    }
    

    Note

    You may see a different value for ObjectId, because it is a system-generated value.

    See also

    For more information on querying data in MongoDB, see Query Documents.

    Summary

    Congratulations! You’ve just set up an Atlas cluster to host your data, and used the mongo shell to write and read data to and from your cluster.

    Insert Data Using the Atlas UI

    Atlas provides a GUI to interact with data in your cluster, called the Data Explorer. You can use the Data Explorer to import sample data provided by Atlas into your cluster.

    To import sample data into your cluster using the Data Explorer:

    1

    Open the Data Explorer.

    From the Atlas Clusters view, click your cluster’s Collections button.

    Screenshot highlighting cluster collections button.
    2

    Click Load a Sample Dataset.

    Image showing the initial Data Explorer screen
    3

    In the ensuing dialog, click Load Sample Dataset to confirm.

    The import takes approximately 5 minutes to complete. Once the operation finishes, the Data Explorer refreshes and you should see the following five databases in your cluster:

    • sample_airbnb
    • sample_geospatial
    • sample_mflix
    • sample_training
    • sample_weatherdata

    For details on the collections and documents included in these datasets, see Available Sample Datasets for Atlas Clusters.

    See also

    For more information on Data Explorer in Atlas, see Perform CRUD Operations in Atlas.

    View and Edit Your Cluster Data

    Estimated completion time: 2 minutes

    Now that you have imported some data into your cluster, you can try viewing and modifying it.

    1

    In the Data Explorer, open the sample_mflix database and select the movies collection.

    Image showing the sample.mflix database
    2

    Search for a specific document.

    You can use the Data Explorer’s Filter bar to search for specific documents. The following query filters the documents in the sample_mflix.movies collection for movies with the title Titanic and the year 1997.

    1. Copy the following filter into your filter bar:

      { "title": "Titanic", "year": 1997 }
      
    2. Click Find.


      Image showing filter in Data Explorer

      The Data Explorer should return a single document after you apply this filter.

    See also

    For more information on querying documents in MongoDB, see Query Documents in the MongoDB manual.

    3

    Edit the Titanic document.

    Now that you have located a specific document in the collection, you can try modifying it.

    1. Hover over the document you filtered for and click the pencil icon icon.



      Image showing how to open the edit document dialog


    2. Hover over the last field in the document and click the appearing plus icon icon.

    3. Click Add Field After num_mflix_comments.



      Image showing adding a new field in edit view.

    4. Create a new field with a key named review. For the value, enter a brief review of the movie. Leave your field’s data type as the default String.



      Image showing adding the review field in edit view.

    5. Click Update to save your changes.

    Additional document interactions

    You can also use the Data Explorer to interact with your documents in the following ways:

    • Copy documents to your system clipboard
    • Clone documents
    • Delete documents

    To perform these operations, hover over your desired document and select the appropriate action.

    Summary

    Congratulations! You have just set up an Atlas cluster to host your data, populated that cluster with sample data, and learned how to interact with that data using the Atlas Data Explorer.

    Moving Forward

    If you continue to grow your cluster, consider scaling your cluster to support more users and operations.