-
Type:
New Feature
-
Resolution: Done
-
Priority:
Trivial - P5
-
None
-
Affects Version/s: None
-
Component/s: None
-
Server Triage
-
None
-
3
-
None
-
None
-
None
-
None
-
None
-
None
Enhance MongoDB to treat embedded documents as first-class entities by:
- Automatically generating unique _id fields for embedded documents (e.g., in arrays or nested objects).
- Supporting an optional type field to define embedded document purpose, with configurable inference.
- Extending CRUD operations (insert, update, delete, find) to target embedded documents directly.
This simplifies managing nested data, reduces client-side logic, and improves data consistency.
Problem
Currently, MongoDB auto-generates _id fields only for top-level documents. Embedded documents (e.g., in arrays like orders) require manual ID assignment, and CRUD operations rely on array operators ($push, $pull, $set) or positional matching. This is cumbersome for complex nested structures.
Proposed Solution
- Auto-Generated _id for Embedded Docs
- Generate an ObjectId for embedded documents during insertion or updates, unless provided.
- Configurable via autoGenerateSubIds: true.
- Optional type Field
- Allow type to categorize embedded docs (e.g., "type": "orderItem").
- Support inference from path (e.g., orders → "orderItem") with inferType: true.
- Extended CRUD Operations
- New syntax:
- insertOne({ "parent": <parent-_id>, "path": <field-path>, "doc": <embedded-doc> })
- updateOne({ "parent": <parent-_id>, "path": <field-path>, "query":
{ "_id": <sub-id> }
, "update": <update-spec> })
- deleteOne({ "parent": <parent-_id>, "path": <field-path>, "query":
{ "_id": <sub-id> }
})
- find({ "parent": <parent-_id>, "path": <field-path>, "query": <sub-query> })
- Example:
javascript
CollapseWrapCopy
{{db.collection.insertOne({
"parent": "parent1",
"path": "orders",
"doc": { "item": "Pencil", "price": 1 },
{ "_id": "parent1", "orders": [ \{ "_id": "auto-gen-1", "type": "orderItem", "item": "Pencil", "price": 1 }
"options": { "autoGenerateSubIds": true, "inferType": true }
});}}Result:
json
CollapseWrapCopy
{{]
}}}
- New syntax:
Use Cases
- E-commerce: Track order items with unique IDs/types.
- Content Systems: Differentiate comments or tags.
- IoT: Manage nested events/readings.
Goals
- Reduce client-side ID generation.
- Enable precise embedded doc operations.
- Improve consistency with typing.
Non-Goals
- Replace $push/$pull (opt-in feature).
- Enforce strict schemas.
Implementation Notes
- Modify src/mongo/db/ops/insert.cpp, update.cpp, query/ for _id/type and path-based ops.
- Use OID::gen() for IDs.
- Add tests in src/mongo/dbtests/.
Acceptance Criteria
- autoGenerateSubIds: true adds unique _id to embedded docs.
- inferType: true sets type from path.
- CRUD ops target embedded docs by _id.
- Existing ops unchanged without new options.
- No performance regression.