複数の文書または必然的に大きなオブジェクト
と以下の文書、MongoDBのを使用しています誰もが、ID参照または埋め込まれた文書を複数のコレクションを使用するかを選択する必要があります。どちらのソリューションも長所と短所を持っています。両方を使用することを学ぶ:
利用別々のコレクション
db.posts.find();
{_id: 1, title: 'unicorns are awesome', ...}
db.comments.find();
{_id: 1, post_id: 1, title: 'i agree', ...}
{_id: 2, post_id: 1, title: 'they kill vampires too!', ...}
使用埋め込まれた文書
db.posts.find();
{_id: 1, title: 'unicorns are awesome', ..., comments: [
{title: 'i agree', ...},
{title: 'they kill vampires too!', ...}
]}
本の
別々のコレクションは最大クエリの柔軟性埋め込まれた文書を選択
// sort comments however you want
db.comments.find({post_id: 3}).sort({votes: -1}).limit(5)
// pull out one or more specific comment(s)
db.comments.find({post_id: 3, user: 'leto'})
// get all of a user's comments joining the posts to get the title
var comments = db.comments.find({user: 'leto'}, {post_id: true})
var postIds = comments.map(function(c) { return c.post_id; });
db.posts.find({_id: {$in: postIds}}, {title: true});
は、そのすべての埋め込まれた文書や配列など、文書
// you can select a range (useful for paging)
// but can't sort, so you are limited to the insertion order
db.posts.find({_id: 3}, {comments: {$slice: [0, 5]}})
// you can select the post without any comments also
db.posts.find({_id: 54}, {comments: -1})
// you can't use the update's position operator ($) for field selections
db.posts.find({'comments.user': 'leto'}, {title: 1, 'comments.$': 1})
より制限され、16メガバイトを超えることはできません提供します。 別々のコレクションの多くの作業が必要
// finding a post + its comments is two queries and requires extra work
// in your code to make it all pretty (or your ODM might do it for you)
db.posts.find({_id: 9001});
db.comments.find({post_id: 9001})
埋め込みドキュメントが
// finding a post + its comments
db.posts.find({_id: 9001});
(シングル求める)挿入と更新
用は大きな違い簡単かつ迅速ません
// separate collection insert and update
db.comments.insert({post_id: 43, title: 'i hate unicrons', user: 'dracula'});
db.comments.update({_id: 4949}, {$set : {title: 'i hate unicorns'}});
// embedded document insert and update
db.posts.update({_id: 43}, {$push: {title: 'lol @ emo vampire', user: 'paul'}})
// this specific update requires that we store an _id with each comment
db.posts.update({'comments._id': 4949}, {$inc:{'comments.$.votes':1}})
個別のドキュメントを選択する必要がある場合や、クエリをより詳細に管理する必要がある場合、または巨大なドキュメントを必要とする場合は、個別のコレクションが適しています。埋め込みドキュメントは、ドキュメント全体、コメント数$のドキュメント、またはコメントのないドキュメントが必要な場合に適しています。一般的なルールとして、「コメント」が多い場合や、大きい場合は別のコレクションが最適な場合があります。文書のサイズが小さくなると、埋め込みのために自然にフィットする傾向があります。
いつでも気をつけてください。両方を試してみるのが最善の方法です。