Query MongoDB Database Collection

This notebook demonstrates how to:

  • Connect to a MongoDB instance
  • List the databases for the instance
  • List the collections for a database
  • Query a database collection and convert the result to a pandas.DataFrame
  • Bind a DataFrame to an jupyter-incubator/declarativewidgets urth-viz-table widget to display the results

In [ ]:
import pandas as pd
from pymongo import MongoClient
from bson.objectid import ObjectId
from urth.widgets.widget_channels import channel

Connect to a MongoDB instance.


In [ ]:
client = MongoClient('192.168.99.100', 27017)

List the databases in the instance.


In [ ]:
client.database_names()

Get a reference to a database.


In [ ]:
db = client.demo

List the collections in the database.


In [ ]:
db.collection_names()

Get a reference to a collection.


In [ ]:
features = db.client_features

Query collection.


In [ ]:
def query_collection(limit=100):
    cursor = features.find({}).limit(limit)
    df = pd.DataFrame(list(cursor))
    # Remove the MongoDB _id column
    del df['_id']
    return df

In [ ]:
df = query_collection()

In [ ]:
df.head()

Show a single record as dict.


In [ ]:
df.iloc[0].to_dict()

Bind the above function to a table widget.


In [ ]:
%%html
<link rel="import" href="urth_components/urth-core-function/urth-core-function.html">
<link rel="import" href="urth_components/urth-viz-table/urth-viz-table.html" is="urth-core-import">

<template is="dom-bind">
    <urth-core-function id="fc" ref="query_collection" 
        arg-limit="{{ limit }}" 
        result="{{ data }}"></urth-core-function>

    <div class="heading layout horizontal justified">
        <button onClick="fc.invoke()">Run Query</button>
    </div>

    <template is="dom-if" if="[[data]]">
        <urth-viz-table
            datarows="{{ data.data }}"
            columns="{{ data.columns }}"
            selection="{{ selected }}"
            rowsVisible=10></urth-viz-table>
    </template>
</template>

In [ ]: