- Install mongodb
- Install pymongo
sudo easy_install pymongo
- Connect with MongoClient
import pymongo
client = pymongo.MongoClient('localhost', 27017)
- Get a Database
db = client.test_db
# OR
db = client['test-db']
- Get a Collection
collection = db.test_collection
# OR
collection = db['test-collection']
- Using insert [db.collection.insert()]
-
document = { 'col1' : 1,
'col2' : 'helloworld',
'col3' : ['val1', 'val2', ],
}
collection.insert(document)
- Using find_one [db.collection.findOne()]
document = collection.find_one()
print document
- Using find [db.collection.find()]
documents = collection.find({ 'query_col' : 'equals this' },
sort=[( 'sort_col', pymongo.ASCENDING )])
- Using remove [db.collection.remove()]
# Remove using a dictionary
document = collection.find_one()
collection.remove(document)
# Remove by ObjectID (document['_id'])
collection.remove('50906d7fa3c412bb040eb577')
- Using update [db.collection.update()/db.collection.upsert()]
document = collection.find_one()
collection.update(document,
{'$set' : { 'add_this_col' : 'new col' } },
upsert = False,
multi = False,
)
0