Kim Spasaro

Running External JavaScript Files on MongoDB

July 4, 2017 ,

Sometimes you need to modify or restructure information in your Mongo database. You can do this easily by writing JavaScript files and running them on your database using your terminal’s mongo command.

A Simple Example

Suppose your Mongo database running at localhost:27017 has a collection for movies and a collection for books. Here’s a simple JavaScript file that finds movies based on books and sets an author field for the movie.

var books = db.books;
var movies = db.movies;
var count = 0;

print('Total books: ' + books.count());
print('Total movies: ' + movies.count());

movies.find().forEach(function(movie){

  var matches = books.find({title: movie.title});

  if(matches.count() > 0){
    
      var book = matches[0];
      movies.update({_id: movie._id}, {$set: {author: book.author}})
      count++;

    }
  }
});

print('Movies updated: ' + count);

You could run this file on your database using your terminal’s mongo command:

mongo localhost:27017/dataBaseName fileName.js

You can also run the file on replica sets and with options like user authorization and SSL.

mongo replicaSetName/nodeUrl.com:port,otherNodeUrl.com:port,anotherNodeUrl.com:port/dataBaseName --authenticationDatabase youAuthenticationDatabase --ssl fileName.js --username yourUsername --password

Using MongoDB’s Atlas hosting, your command might look something like this:

mongo kim-app-shard-0/kim-app-shard-00-00-9abcd.mongodb.net:27017,kim-app-shard-00-01-9abcd.mongodb.net:27017,kim-app-shard-00-02-9abcd.mongodb.net:27017/mymedia --authenticationDatabase admin --ssl addBookAuthorToMovie.js --username kimspasaro --password

Note that the above command will prompt your for your password, but only if the –username and –password flags are provided after the file argument.

And there you have it! Writing scripts to clean or modify your Mongo database is that easy. Check out the Mongo shell reference for a comprehensive list of options you can run when connecting to your database.