Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
// EMBEDDED approach — address lives inside the user document db.users.insertOne({ _id: ObjectId(), name: "Bob", // Address is always fetched with the user, fits well embedded address: { street: "123 Main St", city: "Austin", state: "TX", zip: "78701" } }) // REFERENCE approach — posts reference the author by ObjectId db.authors.insertOne({ _id: ObjectId("aaa111"), name: "Alice" }) db.posts.insertOne({ _id: ObjectId(), title: "MongoDB Design Patterns", // Only store the reference; use $lookup to join when needed authorId: ObjectId("aaa111"), body: "..." }) // Fetch post with author using $lookup (see aggregation topic) db.posts.aggregate([ { $lookup: { from: "authors", localField: "authorId", foreignField: "_id", as: "author" }}, { $unwind: "$author" } ])
Result
Open