Setup & Use Pymongo

  1. Install mongodb
    • [[http://docs.mongodb.org/manual/tutorial/install-mongodb-on-red-hat-centos-or-fedora-linux/|Red Hat Enterprise, CentOS, or Fedora Linux]]
    • [[http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/|Ubuntu]]
    • [[http://docs.mongodb.org/manual/tutorial/install-mongodb-on-debian/|Debian]]
    • [[http://docs.mongodb.org/manual/tutorial/install-mongodb-on-linux/|Generic Linux]]
    • [[http://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/|OS X]]
    • [[http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/|Windows]]
  2. Install pymongo
  3. {{{ lang=sh
    sudo easy_install pymongo
    }}}

  4. Connect with MongoClient
  5. {{{ lang=python
    import pymongo
    client = pymongo.MongoClient(‘localhost’, 27017)
    }}}

  6. Get a Database
  7. {{{ lang=python
    db = client.test_db
    # OR
    db = client[‘test-db’]
    }}}

  8. Get a Collection
  9. {{{ lang=python
    collection = db.test_collection
    # OR
    collection = db[‘test-collection’]
    }}}

  10. Using [[http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert|insert]] [db.collection.insert()]
  11. {{{ lang=python
    document = { ‘col1’ : 1,
    ‘col2’ : ‘helloworld’,
    ‘col3’ : [‘val1’, ‘val2’, ],
    }
    collection.insert(document)
    }}}

  12. Using [[http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one|find_one]] [db.collection.findOne()]
  13. {{{ lang=python
    document = collection.find_one()
    print document
    }}}

  14. Using [[http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find|find]] [db.collection.find()]
  15. {{{ lang=python
    documents = collection.find({ ‘query_col’ : ‘equals this’ },
    sort=[( ‘sort_col’, pymongo.ASCENDING )])
    }}}

  16. Using [[http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.remove|remove]] [db.collection.remove()]
    {{{ lang=python
    # Remove using a dictionary
    document = collection.find_one()
    collection.remove(document)
    # Remove by ObjectID (document[‘_id’])
    collection.remove(‘50906d7fa3c412bb040eb577’)
    }}}

  17. Using [[http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update|update]] [db.collection.update()/db.collection.upsert()]
  18. {{{ lang=python
    document = collection.find_one()
    collection.update(document,
    {‘$set’ : { ‘add_this_col’ : ‘new col’ } },
    upsert = False,
    multi = False,
    )
    }}}


Posted

in

,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *