Tag Archive for Python

Working with MongoDB Stitch Through Existing Drivers – Python & PyMongo

If you are developing an app using Java, Swift, or JavaScript then the Stitch SDK is the best way to access MongoDB Stitch from your frontend application code – getting to your data and accessing your Stitch Services and Functions becomes child’s play.

But, what if you are developing in another language – perhaps running on an app server? Luckily, MongoDB Stitch now supports the MongoDB wire protocol – meaning that you can continue to work with your favorite MongoDB drivers (such as PyMongo) and tools such as the mongo shell.

After enabling connection string access, connecting to your Stitch app from your application is business as usual – just use the connection string you’re shown in the Stitch UI (replacing the username and password with one of your existing Stitch users). This example is for Python, but the pattern is the same for other languages:

>>> import pymongo
>>> from pymongo import MongoClient
>>> client = MongoClient('mongodb://andrewxxxxmorgan%40gmail.com:\
      my_password@stitch.mongodb.com:27020/?authMechanism=PLAIN&\
      authSource=%24external&ssl=true&\
      appName=imported_trackme-etjzr:mongodb-atlas:local-userpass')

Inserting a document should seem very familiar (note that I’m including an owner_id attribute so that the app can take advantage of Stitch’s data access controls):

>>> db = client.trackme
>>> collection = db.comments

>>> comment = {
    "author" : "Andrew Morgan",
    "comment" : "Using Stitch from Python – who knew?!",
    "owner_id" : "5bacd4e7698a67f72dfdb44c"
}
>>> collection.insert_one(comment)

<pymongo.results.InsertOneResult object at 0x102b362d8>

Connecting to MongoDB Stitch using the MongoDB Python Driver

However, Stitch is about more just than accessing MongoDB data. I’ve created a (stupidly) simple Stitch (morning) Function to show how you can execute Stitch Functions through MongoDB drivers:

>>> db.command("callFunction", "morning", arguments=['Billy'])

u'ok': 1, u'response': {u'message': u'Good Morning Billy from andrewxxxxxxorgan@gmail.com'}}

Creating your first Stitch app? Start with one of the Stitch tutorials.

Want to learn more about MongoDB Stitch? Read the white paper.