Example 1 — Profile Sample Data
Imagine profile updates arriving as separate documents. Each has a user and a data object with some fields.
db.profiles.insertMany([
{ user: "sam", data: { city: "New York", role: "dev" } },
{ user: "sam", data: { role: "lead", team: "platform" } },
{ user: "mia", data: { city: "Chicago" } },
{ user: "mia", data: { team: "design", city: "Austin" } }
]); How the Data Is Stored in MongoDB
After the insert, MongoDB keeps 4 documents in profiles. Run find() to see them:
db.profiles.find() Read each document like this:
| Field in MongoDB | Meaning | Example |
|---|---|---|
user | Whose profile patch this is | "sam" |
data | Object fields to merge | { role: "lead" } |
Sam patches:
1) { city: "New York", role: "dev" }
2) { role: "lead", team: "platform" }
$mergeObjects combines them (later keys win on conflict). How It Works
- Insert once. The sample command adds 4 documents to
profiles. - MongoDB stores fields as written. Each document keeps the same field names and values you inserted.
- find() shows the same shape. What you inserted is what you get back—ready for
$mergeObjectsin the next examples.

