This post was written for Nodejitsu blog and is crossposted here. Nodejitsu loved what I was doing at and is now supporting the project.

NeDB (GitHub: louischatriot/nedb, License: MIT) by Louis Chatriot is an embedded persistent database with no dependencies. It implements a subset of the most used MongoDB operations and is currently considered stable. You can use NeDB as an in-memory only datastore or as a persistent datastore. One datastore is the equivalent of a MongoDB collection. Lets have a look.

npm install nedb


Below is the breif summary of the API. As you can see it’s pretty much one for one with MongoDB. The cool part is that NeDB can also run in the browser on top of local storage.

  • Creating/loading a database
  • Compacting the database
  • Inserting documents
  • Finding documents
    • Basic Querying
    • Operators ($lt, $lte, $gt, $gte, $in, $nin, $ne, $exists, $regex)
    • Array fields
    • Logical operators $or, $and, $not, $where
    • Sorting and paginating
    • Projections
  • Counting documents
  • Updating documents
  • Removing documents
  • Indexing
  • Browser version

Here’s a quick example that counts number of times the script was executed.

var Datastore = require('nedb');
var db = new Datastore({ filename: __dirname + '/db.json', autoload: true });

db.findOne({ _id: 1 }, function (err, doc) {
  doc = doc || { _id: 1, counter: 0 };

  console.log('This example was executed ' + doc.counter + ' times. Last access time was ' + doc.lastSeetAt);

  doc.lastSeetAt = new Date();

  db.update({ _id: 1 }, doc, { upsert: true }, function (err, num) {
    console.log('Updated ' + num + ' records');

The db.json would looks like this.

Under the hood, NeDB’s persistence uses an append-only format, meaning that all updates and deletes actually result in lines added at the end of the datafile. The reason for this is that disk space is very cheap and appends are much faster than rewrites since they don’t do a seek. The database is automatically compacted (i.e. put back in the one-line-per-document format) everytime your application restarts.


What Else?

Checkout the runnable example and github example repository.