Category Archives: mongo

Tip: List non replication operations when using db.currentOp() in the MongoDb shell

We run ad-hoc queries against our MongoDB hidden slaves pretty frequently at work. Some of these queries are long running so it nice to be get a filtered view of what operations are running without all the replication operations that are constantly running.

The mongo shell is a javascript interpreter so that is easy to do:

db.currentOp()["inprog"].filter(function(x) { return !x.desc.match(/repl.*/); });

Tip: A shortcut for accessing another MongoDB database from the shell

At uSwitch, I often work with multiple MongoDB databases as part of the same system. Recently I spent a lot of time in the Mongo shell jumping between the two databases to reset data to its initial state.

This requires several commands

use otherdb;
db.collectionx.remove();

use originaldb;
db.collectiony.remove();

Plus I often forget which database I’m in.

Happily you can use the db.getSiblingDB method to access another database without having to switch databases. This shorten it down to a single command:

db.getSiblingDB("otherdb").collectionx.remove();
db.getSiblingDB("originaldb").collectiony.remove();

Stripping strings in a Mongoid document

When taking in user input on a web form you usually want to strip/trim the text the user has entered. I wrote a little Mongoid extension class to do this. The fields need to explicitly declared for this to work. To use it just add include Mongoid::StringStripper to your document class.

module Mongoid
  module StringStripper
    extend ActiveSupport::Concern

      included do
        set_callback :save, :before, :strip_strings
      end

      def strip_strings
        field_names = fields.map {|x| x[0] }.reject{ |x| x[0] == "_"  }
        field_names.each do |field_name|
          value = self.send(field_name)
          if value and value.respond_to?(:strip)
            self.send(field_name + "=", value.strip)
          end
        end
      end
  end
end

Here is usage example/test:

require 'test_helper'

class TestStippee
  include Mongoid::Document
  include Mongoid::StringStripper

  field :a, type: String
  field :b, type: String
  field :c, type: Integer

end

class StringStripperTest < ActiveSupport::TestCase
  test "When mongoid doc is saved the strings are stripped" do
    o = TestStippee.new(:a => "stripped ", :b => "unchanged", :c => 1)
    o.save
    assert_equal o.a, "stripped"
    assert_equal o.b, "unchanged"
    assert_equal o.c, 1
  end
end