Skip to content

Instantly share code, notes, and snippets.

@marians
Last active January 15, 2026 01:46
Show Gist options
  • Select an option

  • Save marians/8e41fc817f04de7c4a70 to your computer and use it in GitHub Desktop.

Select an option

Save marians/8e41fc817f04de7c4a70 to your computer and use it in GitHub Desktop.
The missing Python couchdb tutorial

This is an unofficial manual for the couchdb Python module I wish I had had.

Installation

pip install couchdb

Importing the module

import couchdb

Connection

If you only need read access, use an anonymous connection:

couchserver = couchdb.Server("http://couchdb:5984/")

To write to the database, create an authenticated connection:

user = "admin"
password = "my secret password"
couchserver = couchdb.Server("http://%s:%s@couchdb:5984/" % (user, password))

Listing databases

Simply iterate over the server object like this:

for dbname in couchserver:
    print(dbname)

Selecting/creating a database to work with

dbname = "mydb"
if dbname in couchserver:
    db = couchserver[dbname]
else:
    db = couchserver.create(dbname)

Deleting a database

del couchserver[dbname]

Writing a document to a database

Storing a document with an auto-generated ID:

doc_id, doc_rev = db.save({'key': 'value'})

doc_id is the generated document ID, doc_rev is the revision identifier.

Setting a specific ID:

db["my_document_id"] = {'key': 'value'}

Writing multiple documents in one call is done via the update() method of the database object. This can either create new documents (when no _id field is present per document) or update existing ones.

docs = [{'key': 'value1'}, {'key': 'value2'}]
for (success, doc_id, revision_or_exception) in db.update(docs):
    print(success, docid, revision_or_exception)

Retrieving documents by ID

doc_id = "my_document_id"
doc = db[doc_id]  # or db.get(doc_id)

Querying documents from views

If your database has a design document and view under the path /db_name/_design/design_doc/_view/view_name, you can iterate this view using this syntax:

for item in db.view('design_doc/view_name'):
    print(item.key, item.id, item.value)

Limiting the output to a certain number of items:

for item in db.view('design_doc/view_name', limit=100):
    print(item.key, item.id, item.value)

Skipping the first n items:

for item in db.view('design_doc/view_name', skip=100):
    print(item.key, item.id, item.value)

Reverse sorting:

for item in db.view('design_doc/view_name', descending=True):
    print(item.key, item.id, item.value)

Including source documents in result entries:

for item in db.view('design_doc/view_name', include_docs=True):
    print(item.key, item.id, item.value)

Allow outdated data to be returned, prevent updating the view before returning results:

for item in db.view('design_doc/view_name', stale="ok"):
    print(item.key, item.id, item.value)

Update the view after returning the results:

for item in db.view('design_doc/view_name', stale="update_after"):
    print(item.key, item.id, item.value)

Grouping results

Grouping the results by key, using the Reduce function, must be activated explicitly:

for item in db.view('design_doc/view_name', group=True):
    print(item.key, item.value)

If the Map function emits a structured key (an array with multiple elements), the grouping level can be determined:

for item in db.view('design_doc/view_name', group=True, group_level=1):
    print(item.key, item.value)

Filtering

Return only entries from the view matching a certain key:

for item in db.view('design_doc/view_name', key="my_key"):
    print(item.key, item.id, item.value)

Return entries with keys in a certain range:

for item in db.view('design_doc/view_name', startkey="startkey", endkey="endkey"):
    print(item.key, item.id, item.value)

The key, startkey and endkey parameters also accept arrays, e. g.

for item in db.view('design_doc/view_name', startkey=["foo", "a"], endkey=["foo", "z"]):
    print(item.key, item.id, item.value)
@fedesn
Copy link

fedesn commented Jan 25, 2018

very good mate, thanks a lot.

@nicoddemus
Copy link

Thanks for this!

@Shin-Aska
Copy link

very very helpful!

@StoneSwine
Copy link

This is great! Thanks

@niuguy
Copy link

niuguy commented May 15, 2018

Great work, thanks!

@SunilDSK
Copy link

Good work! Thanks a lot.

@akshaysin
Copy link

Excellent. Thanks a lot

@ruzzuq
Copy link

ruzzuq commented Oct 13, 2018

thanks a lot

@alibanaei
Copy link

👍 👍

@allanaguilar
Copy link

thnks!!!!!

@rmshkmr
Copy link

rmshkmr commented Mar 22, 2019

awesome

@PeggyZWY
Copy link

PeggyZWY commented Jun 1, 2019

Thanks!!

@visuddha
Copy link

Thanks!!

@chuenniger
Copy link

Hi

can you add this to your List? :)

Indexes

Create an index

index = db.index()
index.__setitem__(
    {"ddocname", "index-namE"},
    ['foor', 'bar']
)

@Junduo123
Copy link

Thanks, saving time than searching tutorials online

@PlutarcoII
Copy link

PlutarcoII commented Jan 13, 2020

Save attachment file to disk

doc = db[doc_id]
nameFile = doc['_attachments'].keys()[0]
attachment = db.get_attachment(doc, nameFile).read()
current_folder = os.getcwd()
tempfile = os.path.join(current_folder, nameFile)
f= open(tempfile, 'w')
f.write(attachment)
f.close()    

@KailunHuang
Copy link

thank you mate

@DanRuderman
Copy link

Much appreciated!

@4lberto
Copy link

4lberto commented Oct 21, 2020

Very hepful

@marians
Copy link
Author

marians commented Oct 21, 2020

Since I am currently not working with CouchDB, it would take some extra effort to verify the additions made here in the comment. Please understand that I don't add them to the doc without verification.

Anyway, keep adding tips via comments and help those that come by after you!

@raffaelemancuso
Copy link

Notice that the couchdb python package is now abandoned

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment