Read Data from MongoDB

Deployment Type:
Client:

    Author: MongoDB Documentation Team

    You will retrieve data from 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.

    Switch to the database you wish to query. In this case we will be using test.

    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

    Retrieve all documents in the inventory collection.

    myCursor = db.inventory.find( {} )
    

    Select the test database in the list of available databases.

    Then select the inventory collection to view all documents in the collection.

    cursor = db.inventory.find({})
    

    First you will need to create the MongoCollection object you would like to query against.

    MongoCollection<Document> collection = db.getCollection("inventory");
    

    Then query the collection for all documents by passing an empty document to the find() method.

    FindIterable<Document> findIterable = collection.find(new Document());
    
    var cursor = db.collection('inventory').find({});
    
    cursor = db.inventory.find({})
    

    For completeness, this is how you might wrap the call and run it in an asyncio loop:

    async def do_find():
        cursor = db.inventory.find({})
        async for doc in cursor:
           pprint.pprint(doc)
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(do_find())
    
    var filter = Builders<BsonDocument>.Filter.Empty;
    var result = collection.Find(filter).ToList();
    
    4

    Iterate over the results.

    This query does not require cursor iteration in mongo shell because the shell returns up to 20 results.

    You will see a list of all of the documents that match your criteria in the query window.

    from pprint import pprint
    
    for inventory in cursor:
         pprint(inventory)
    

    You can implement a com.mongodb.Block to print the results of the iteration

    Block<Document> printBlock = new Block<Document>() {
        @Override
        public void apply(final Document document) {
            System.out.println(document.toJson());
        }
    };
    

    Then iterate the cursor for documents, passing the printBlock as a parameter.

    findIterable.forEach(printBlock);
    
    function iterateFunc(doc) {
       console.log(JSON.stringify(doc, null, 4));
    }
    
    function errorFunc(error) {
       console.log(error);
    }
    
    cursor.forEach(iterateFunc, errorFunc);
    

    In the code snippet above you may have noticed the code that iterates the results and prints them to the command line:

    async for doc in cursor:
        print(doc)
    
    foreach (var doc in result) {
       Console.WriteLine(doc.ToJson());
    }
    
    5

    Check your results.

    If you loaded the data from Insert Data into MongoDB, you should see output that resembles the following:

    Note

    Your ObjectId values will differ from those shown.

    { "_id" : ObjectId("5a9854915c8eb0d368732649"),
      "item" : "canvas",
      "qty" : 100,
      "tags" : [ "cotton" ],
      "size" : {
                  "h" : 28,
                  "w" : 35.5,
                  "uom" : "cm"
               }
    }
    
    Screenshot of Compass result grid
    {u'_id': ObjectId('5ada5bdeaea650851c715601'),
    u'item': u'canvas',
    u'qty': 101,
    u'size': {u'h': 28, u'uom': u'cm', u'w': 35.5},
    u'tags': [u'cotton']}
    
    { "_id" : { "$oid" : "5ada85ae9b267e9ac4d84105" }, "item" : "canvas", "qty" : 100, "tags" : ["cotton"], "size" : { "h" : 28, "w" : 35.5, "uom" : "cm" } }
    
    { _id: 5ade4124aac4f92cf89f53aa,
      item: 'journal',
      qty: 25,
      size: { h: 14, w: 21, uom: 'cm' },
      status: 'A' }
    
    {'_id': ObjectId('5adb4ee0aea650d05134bf62'), 'item': 'canvas', 'qty': 100, 'tags': ['cotton'], 'size': {'h': 28, 'w': 35.5, 'uom': 'cm'}}
    
    { "_id" : ObjectId("5ade1ebd9299811bc223e797"), "item" : "canvas", "qty" : 100, "tags" : ["cotton"], "size" : { "h" : 28, "w" : 35.5, "uom" : "cm" } #}
    

    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 retrieved data from MongoDB. In the next guide, you will use queries to find data in your collection that matches specified criteria.

    What’s Next

    In the next guide, you’ll learn how to retrieve data from MongoDB using criteria.