Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique field in pymongo

Tags:

flask

pymongo

What is the simplest way to avoid field collisions working with pymongo? I have a very simple structure for a Location class (name, slug, description and geolocation) and I would like to ensure that no duplicate names are allowed. I am using flask and pymongo?

I was trying this:

from flask import Flask

from flask.ext.pymongo import PyMongo


app = Flask(__name__)

mongo = PyMongo(app)

mongo.db.court.ensureIndex( { "name": 1, "slug": 1 } )

but it gives me an error: RuntimeError: working outside of application context.

like image 608
freethrow Avatar asked Sep 17 '13 20:09

freethrow


2 Answers

use unique indexes and you'll have no two documents that have same values for a field. this doesn't have to be flask-specific, but it is rather mongodb-specific.

if you're lazy or indexes give you headache, just use _id field as the location name. in this case you have to make sure your documents don't get overwritten.

like image 181
thkang Avatar answered Nov 11 '22 04:11

thkang


The best place to put your calls to ensure_index is someplace before you call run() on your flask app. You want to make sure your indexes are in place before you attempt to service any requests, because building the index while the site is live will make it pretty unresponsive. The error you are getting is because you need the application context. Try:

app = Flask(__name__)
mongo = PyMongo(app)
if __name__ == '__main__':
    with app.app_context():
        mongo.db.court.ensure_index( [("name", ASCENDING), ("slug", ASCENDING)], unique=True )
    app.run()

As @thkang said, you should use a unique index to enforce that no two documents have the same value for a field or set of fields taken together. See more about this and pymongo's ensure_index syntax at the pymongo docs.

like image 38
llovett Avatar answered Nov 11 '22 06:11

llovett