Get all DocumentDB Collections from Node.js

06 Nov 2015

Yesterday I wrote about how to get all databases in a DocumentDB account. Here’s a quick little snippet on how to list out all collections in a DocumentDB account (and correlate them with their containing database)…

var DocumentClient = require('documentdb').DocumentClient;

var endpointUrl = '... url ...';
var masterKey = '... key ...';
var ddbClient = new DocumentClient(endpointUrl, {masterKey: masterKey});

ddbClient.queryDatabases('SELECT d.id, d._self FROM databases d')
    .forEach(function (err, database) {
        if (database) {
            console.log(database.id + ' -- ' + database._self);
            ddbClient.queryCollections(database._self, 'SELECT c.id, c._self FROM collections c')
                .forEach(function (err, collection) {
                    if (collection) {
                        console.log('  ' + collection.id + ' -- ' + collection._self);
                    }
                });
        }
    });

This can be handy to dump out all of the collections in your DocumentDB account.

Enjoy!

EDIT

Ryan CrawCour (@ryancrawcour), a Program Manager on the DocumentDB team, introduced me to an ever better way to pull this information. You can simply use readDatabases() and readCollections() to get this information in a much easier-to-write-and-read snippet…

ddbClient.readDatabases()
    .forEach(function (err, database) {
        if (database) {
            console.log(database.id + ' -- ' + database._self);
            ddbClient.readCollections(database._self)
                .forEach(function (err, collection) {
                    if (collection) {
                        console.log('  ' + collection.id + ' -- ' + collection._self);
                    }
                });
        }
    });

Thanks, Ryan!