How to Insert Nested Document in MongoDB: Simple Guide
To insert a nested document in MongoDB, use the
insertOne() method with a JSON object that contains another JSON object as a field. The nested document is simply a key-value pair where the value is another document inside the main document.Syntax
The basic syntax to insert a nested document in MongoDB uses the insertOne() method on a collection. The document you insert can have fields whose values are other documents (nested objects).
- collection.insertOne(document): Inserts one document into the collection.
- document: A JSON object that can include nested JSON objects as values.
mongodb
db.collection.insertOne({
field1: "value1",
nestedField: {
subField1: "subValue1",
subField2: 123
}
})Example
This example shows how to insert a user document with a nested address document inside it. The nested document groups related address fields together.
mongodb
db.users.insertOne({
name: "Alice",
age: 30,
address: {
street: "123 Maple St",
city: "Springfield",
zip: "12345"
}
})Output
{ "acknowledged" : true, "insertedId" : ObjectId("someObjectId") }
Common Pitfalls
Common mistakes when inserting nested documents include:
- Using incorrect syntax like strings instead of objects for nested fields.
- Forgetting to use curly braces
{}for nested documents. - Trying to insert arrays when an object is expected or vice versa.
Always ensure nested documents are valid JSON objects.
mongodb
/* Wrong: nestedField as string instead of object */ db.collection.insertOne({ field1: "value1", nestedField: "should be an object, not a string" }) /* Right: nestedField as object */ db.collection.insertOne({ field1: "value1", nestedField: { subField1: "subValue1" } })
Quick Reference
Tips for inserting nested documents:
- Use
insertOne()orinsertMany()to add documents. - Nested documents are JSON objects inside fields.
- Use curly braces
{}to define nested objects. - Validate your document structure before inserting.
Key Takeaways
Use insertOne() with a JSON object containing nested objects to insert nested documents.
Nested documents are just fields whose values are other JSON objects inside the main document.
Always use curly braces {} to define nested documents correctly.
Avoid using strings or arrays where an object is expected for nested fields.
Validate your document structure to prevent insertion errors.