Skip to content
Mongolian DeadBeef is an awesome Mongo DB driver for node.js
Find file
New pull request
Pull request Compare This branch is 108 commits behind marcello3d:master.
Fetching latest commit...
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.

Mongolian DeadBeef

Mongolian DeadBeef is an awesome Mongo DB node.js driver that sits on top of node-mongodb-native and attempts to closely approximate the mongodb shell.


Mongolian DeadBeef and its documentation is super under construction! Go check out examples/mongolian_trainer.js and the rest of the source!


WARNING! The API is super experimental, and will be adding, removing, and changing the API regularly. Use at your own risk

You can either clone the source and install with npm link, or install the latest published version from npm with npm install mongolian.

Running Tests

Run the tests with npm test.


Not a fan of existing asynchronous mongodb apis for node.js, I set out to write my own. To avoid completely reinventing the wheel, much of the Mongolian DeadBeef API is inspired by the mongodb shell.

High level principles:

  • Less is more
    • Nothing is added without careful consideration
    • Remove everything but the essentials
    • Each refactor should remove as much unnecessary lines of code as possible
  • Fail early and often
    • If I can easily detect a programmer error, an exception will be thrown


  • mongodb is pretty simple, much of its functionality is defined as queries on special databases
    • This allows for lots of code reuse
  • Avoid callbacks unless they are absolutely necessary


Most of the work in MongolianDeadBeef doesn't occur until a query is actually made. This means that simple operations are fast and synchronous. Currently there is one connection per server. You can have multiple queries simultaneously on a single mongodb connection, so I'm not sure how important pooling is at this point.


var Mongolian = require("mongolian")

// Create a server instance with default host and port
var server = new Mongolian

// Get database
var db = server.db("awesome_blog")

// Get some collections
var posts = db.collection("posts")
var comments = db.collection("comments")

// Insert some data
    pageId: "hallo"
    title: "Hallo",
    created: new Date,
    body: "Welcome to my new blog!"

// Get a single document
posts.findOne({ pageId: "hallo" }, function(err, post) {

// Document cursors
posts.find().limit(5).sort({ created: 1 }).toArray(function (err, array) {
    // do something with the array
posts.find({ title: /^hal/ }).forEach(function (post) {
    // do something with a single post
}, function(err) {
    // handle errors/completion

Extended Examples

// Create a server with a specific host/port
var server = new Mongolian({

// Create a server with a 15 second connection keep-alive
var server = new Mongolian({ keepAlive:15000 })

// Authenticate a database
db.auth(username, password)

// GridFS
var gridfs = db.gridfs()

// Writing to GridFS consists of creating a GridFS file:
var file = gridfs.create({
// And getting writable Stream (see )
var stream = file.writeStream()

// You can then pipe a local file to that stream easily with:

// Reading a file from GridFS is similar:
gridfs.findOne("License", function (err, file) {
    if (!err && file) {
        // Get the read stream:
        var stream = file.readStream()

        // You could then pipe the file out to a http response, for example:

Mongodb Shell Command Support

Nearly all commands are identical in syntax to the mongodb shell. However, asynchronous commands that go to the server will have an optional node.js style callback parameter.

Currently most commands starting with get are named without the get. Some of the getters are implemented as values instead of functions.

  • Bold functions are supported
  • Italicized functions are supported with different syntax
  • Everything else is currently unsupported

There will likely be methods below that are never supported by Mongolian DeadBeef, since I'm targetting a slightly different use case.



  • db.addUser(username, password[, readOnly=false][, callback])
  • db.auth(username, password)
  • db.cloneDatabase(fromhost)
  • db.commandHelp(name) returns the help for the command
  • db.copyDatabase(fromdb, todb, fromhost)
  • db.createCollection(name, { size : ..., capped : ..., max : ... } )
  • db.currentOp() displays the current operation in the db
  • db.dropDatabase() - see callback note below
  • db.eval(func[, arg1, arg2, ...][, callback]) run code server-side - see callback note below
  • db.getCollection(cname) implemented as db.collection(cname)
  • db.getCollectionNames() implemented as db.collectionNames(callback)
  • db.getLastError() - just returns the err msg string
  • db.getLastErrorObj() implemented as db.lastError(callback) - return full status object
  • db.getMongo() get the server connection object implemented as db.server
  • db.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair
  • db.getName() implemented as
  • db.getPrevError() (deprecated?)
  • db.getProfilingStatus() - returns if profiling is on and slow threshold
  • db.getReplicationInfo()
  • db.getSiblingDB(name) get the db at the same server as this one
  • db.isMaster() check replica primary status
  • db.killOp(opid) kills the current operation in the db
  • db.listCommands() lists all the db commands
  • db.printCollectionStats()
  • db.printReplicationInfo()
  • db.printSlaveReplicationInfo()
  • db.printShardingStatus()
  • db.removeUser(username[, callback]) - see callback note below
  • db.repairDatabase()
  • db.resetError()
  • db.runCommand(cmdObj[, callback]) run a database command. if cmdObj is a string, turns it into { cmdObj : 1 }
  • db.serverStatus()
  • db.setProfilingLevel(level,) 0=off 1=slow 2=all
  • db.shutdownServer()
  • db.stats()
  • db.version() current version of the server



  • collection.find().help() - show DBCursor help
  • collection.count(callback)
  • collection.dataSize()
  • collection.distinct( key ) - eg. collection.distinct( 'x' )
  • collection.drop([callback]) drop the collection - see callback note below
  • collection.dropIndex(name[, callback]) - see callback note below
  • collection.dropIndexes()
  • collection.ensureIndex(keypattern[,options][, callback]) - options is an object with these possible fields: name, unique, dropDups - see callback note below
  • collection.reIndex()
  • collection.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return. e.g. collection.find( {x:77} , {name:1, x:1} ) - returns a cursor object
  • collection.find(...).count()
  • collection.find(...).limit(n)
  • collection.find(...).skip(n)
  • collection.find(...).sort(...)
  • collection.findOne([query][callback])
  • collection.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )
  • collection.getDB() get DB object associated with collection implemented as collection.db
  • collection.getIndexes() implemented as collection.indexes(callback)
  • { key : ..., initial: ..., reduce : ...[, cond: ...] } )
  • collection.mapReduce( mapFunction , reduceFunction , [optional params][, callback])
  • collection.remove(query[, callback]) - see callback note below
  • collection.renameCollection( newName , [dropTarget] ) renames the collection.
  • collection.runCommand( name , [options] ) runs a db command with the given name where the first param is the collection name
  •[, callback]) - see callback note below
  • collection.stats()
  • collection.storageSize() - includes free space allocated to this collection
  • collection.totalIndexSize() - size in bytes of all the indexes
  • collection.totalSize() - storage allocated for all data and indexes
  • collection.update(query, object[, upsert_bool, multi_bool][, callback]) - see callback note below
  • collection.validate() - SLOW
  • collection.getShardVersion() - only for use with sharding



  • cursor.sort( {...} )
  • cursor.limit( n )
  • cursor.skip( n )
  • cursor.count() - total # of objects matching query, ignores skip,limit
  • cursor.size() - total # of objects cursor would return, honors skip,limit
  • cursor.explain([verbose])
  • cursor.hint(...)
  • cursor.showDiskLoc() - adds a $diskLoc field to each returned object
  • cursor.toArray(callback) - unique to Mongolian DeadBeef
  • cursor.forEach(func, callback) - calls func for each element, and callback upon completion or error
  • cursor.print() - output to console in full pretty format
  • func )
  • cursor.hasNext()
  •[callback]) - executes callback(null) if there are no more elements


Callbacks take the standard node.js format: function(error, value)

Mongodb handles write operations (insert, update, save, drop, etc.) asynchronously. If you pass a callback into one of these methods, this is equivalent to immediately calling db.lastError(callback) on the same server/connection. Passing a null value will not send a getLastError command to the server.

Currently there is no way to specify the write concern on these inlined callbacks.


  • Various utility methods
  • More unit tests
  • Documentation
  • Connection pooling
  • Cleanup


Try it out and send me feedback! That's the best help I could use right now. Unit tests are good, too.


Mongolian DeadBeef is open source software under the zlib license.

Something went wrong with that request. Please try again.