PyMongo (API reference) is the Python API provided by MongoDB, a key-value document store.
The latest version is 3.7, supporting MongoDB versions 2.6, 3.0, 3.2, 3.4 and 3.6 In the API summary below, version 2.8 APIs are given in parens after the 3.7 API.
Connecting, getting a database handle, getting a collection:
from pymongo import MongoClient
client = MongoClient('localhost', 27017) # or 'mongodb://localhost:27017/'
db = client['test_database']
db = client.test_database
collection = db['test_collection']
collection = db.test_collection
Asking a client for an invalid database name will raise InvalidName.
server_info()
See current and version 2.8 API docs.
client
(connection
): The client instance for the DBcommand(...)
: Issue a MongoDB commandlist_collection_names()
(≤3.6:collection_names()
) Get a list of collections in the DB.include_system_collections=False
is a default paramlist_collections()
(≥3.6): Return aCommandCursor
over the collections in the DBcreate_collection(name, **kwargs)
: Normally collection creation is automatic, but this can be used if you need to set optionsdrop_collection(name_or_collection)
Documents are represented in Python by dictionaries.
See current and version 2.8 API docs.
Collection information:
name
,full_name
database
rename(new_name)
: Rename collectiondrop()
: Alias forDatabase.drop_collection()
Searching/retrieval:
count_documents()
(<3.7:count()
)estimated_document_count()
(≥3.7): Estimate from metadatafind()
: returns a Cursorfind_one()
: Returns a single document orNone
Inserts/updates/deletes:
insert_one()
,insert_many()
(<3.0:insert()
)replace_one()
,update_one()
,update_many()
delete_one()
,delete_many()
Deprecated:
save
: Use{insert,replace}_one()
update()
: Usereplace_one()
orupdate_{one,many}()
remove()
: Usedelete_{one,many}()
find_and_modify()
: Usefind_one_and_{delete,replace,update}()
The tutorial may be useful.
Write a document:
doc = { 'name': 'test', 'value': 42, }
oid = collection.insert_one(doc)
oid ⇒ ObjectId('5b35e112055dd50014002f1b')
collection.find_one(_id = oid) ⇒ {'name': 'test', 'value': 42,
'_id': ObjectId('5b35e112055dd50014002f1b')}
Query:
collection.find({'afield': re.compile('^foo')}).count()
Ref. query operators.