Various changes to support storage in mongo db (first version that works to some extent)