How to import data from mongodb to pandas ?

How to import data from mongodb to pandas ?

Asked on December 21, 2018 in Pandas.
Add Comment


  • 2 Answer(s)

    The function pymongo can be used:

    import pandas as pd
    from pymongo import MongoClient
     
    def _connect_mongo(host, port, username, password, db):
        """ A util for making a connection to mongo """
     
        if username and password:
            mongo_uri = 'mongodb://%s:%[email protected]%s:%s/%s' % (username, password, host, port, db)
            conn = MongoClient(mongo_uri)
        else:
            conn = MongoClient(host, port)
     
        return conn[db]
     
    def read_mongo(db, collection, query={}, host='localhost', port=27017, username=None, password=None,  no_id=True):
        """ Read from Mongo and Store into DataFrame """
     
        # Connect to MongoDB
        db = _connect_mongo(host=host, port=port, username=username, password=password, db=db)
     
        # Make a query to the specific DB and Collection
        cursor = db[collection].find(query)
     
        # Expand the cursor and construct the DataFrame
        df = pd.DataFrame(list(cursor))
     
        # Delete the _id
        if no_id:
        del df['_id']
     
        return df
    
    Answered on December 21, 2018.
    Add Comment

    The below code is used to load mongodb data to pandas DataFrame:

    import pymongo
    import pandas as pd
    from pymongo import MongoClient
    client = MongoClient()
    db = client.database_name
    collection = db.collection_name
    data = pd.DataFrame(list(collection.find()))
    
    Answered on December 21, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.