Add support for passing in a mongodb.Db instance

Plus some minor code moving