MongoDB index scripting

<< Of Image Exif, PropertyItem and reflection | Home | Operations in action–Marking WCF interface as down for maintenance >>

Say you liked the indexes you created on system A and wanted them on system B.

Say you are a horrible typist.

Say you are reading this blog, and are good at COPY+PASTE.

@ECHO OFF

SET HOST=eqcmongo01.eq.colo/

SET DB=Photologica

mongo %HOSt%%DB% --quiet --eval "db.system.indexes.find({'key._id':{$exists:false}}).forEach(function(c){ print(c.ns.replace('%DB%','db') + '.ensureIndex('); printjson(c.key); print( ');');})"

The recipe is:

  • Run mongo shell in quiet mode.
  • Query out the indexes except the "natural" _id ones (although not a problem to script out, this is noise)
  • Output an ensureIndex command for each index.
  • Run the batch file, redirect output into a indexExport.js file.
  • Run mongo [target server] indexExport.js

Well, this is kind of cool. You might be thinking there's an in-shell way of doing the same. You are correct.

One reason to create a file artifact is that you can source-control it and repeat the process when bringing up new environments.

Monday, February 20, 2012 1:56 PM

This article is part of the GWB Archives. Original Author: Nuri Halperin

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.