Schema evolution Schema Design 102 - Common patterns • Single table inheritance • One-to-Many & Many-to-Many • Trees • Queues Schema design is easy! • Data as Objects in code
db.posts.ensureIndex({"comments.author": 1}) > db.posts.find({"comments.author":"Kyle"}) // find last 5 posts: > db.posts.find().sort({date:-1}).limit(5) // most commented post: db.posts.find().sort({comments_count:-1}).limit(1) When sorting, check if you need an index
30 ] } categories: { _id: 20, name: "adventure"} // All products for a given category > db.products.find({category_ids: 20)}) // All categories for a given product > product = db.products.find(_id : some_id) > db.categories.find({_id : {$in : product.category_ids}}) Alternative
_id: "a" } { _id: "b", thread: [ "a" ], replyTo: "a" } { _id: "c", thread: [ "a", "b" ], replyTo: "b" } { _id: "d", thread: [ "a", "b" ], replyTo: "b" } { _id: "e", thread: [ "a" ], replyTo: "a" } { _id: "f", thread: [ "a", "e" ], replyTo: "e" } // find all threads where "b" is in > db.msg_tree.find({thread: "b"}) A B C D E F
_id: "a" } { _id: "b", thread: [ "a" ], replyTo: "a" } { _id: "c", thread: [ "a", "b" ], replyTo: "b" } { _id: "d", thread: [ "a", "b" ], replyTo: "b" } { _id: "e", thread: [ "a" ], replyTo: "a" } { _id: "f", thread: [ "a", "e" ], replyTo: "e" } // find all threads where "b" is in > db.msg_tree.find({thread: "b"}) // find all direct message "b: replied to > db.msg_tree.find({replyTo: "b"}) A B C D E F
Separate each node by a delimiter, e.g. “/” - Use text search for find parts of a tree { comments: [ { author: "Kyle", text: "initial post", path: "" }, { author: "Jim", text: "jim’s comment", path: "jim" }, { author: "Kyle", text: "Kyle’s reply to Jim", path : "jim/kyle"} ] } // Find the conversations Jim was part of > db.posts.find({path: /^jim/i})
to the database •DBCollection coll = new Mongo().getDB("blogs"); // Create the Object •Map<String, Object> obj = new HashMap... •obj.add("author", "Hergé"); •obj.add("text", "Destination Moon"); •obj.add("date", new Date()); // Insert the object into MongoDB •coll.insert(new BasicDBObject(obj));
the data store • Datastore ds = new Morphia().createDatastore() • // Create the Object • Blog entry = new Blog("Hergé", New Date(), "Destination Moon") • // Insert object into MongoDB • ds.save(entry);
data design principles stay the same • Focus on how the application manipulates data • Rapidly evolve schema to meet your requirements • Enjoy your new freedom, use it wisely :-)