Insert Document
Inserts one or more documents into a MongoDB collection.
Common Properties
- Name - The custom name of the node.
- Color - The custom color of the node.
- Delay Before (sec) - Waits in seconds before executing the node.
- Delay After (sec) - Waits in seconds after executing node.
- Continue On Error - Automation will continue regardless of any error. The default value is false.
If the ContinueOnError property is true, no error is caught when the project is executed, even if a Catch node is used.
Inputs
- MongoDB Client Id - The client ID returned from the Connect node (optional if credentials are provided).
- Database Name - The name of the database containing the collection.
- Collection Name - The name of the collection to insert documents into.
- MongoDB Query - Document(s) to insert in JSON format. Can be:
- A single JSON object for inserting one document
- An array of JSON objects for inserting multiple documents
Options
- Credentials - Database credentials (Category 5) - optional if using Client ID from Connect node. This allows you to perform the operation without a separate Connect node.
How It Works
The Insert Document node adds new documents to a MongoDB collection. When executed, the node:
- Validates that database name and collection name are not empty
- Obtains a MongoDB client (either from client ID or by creating one from credentials)
- Processes the MongoDB Query input with Handlebars template rendering
- Parses the rendered JSON into BSON format
- Determines if it's a single document or multiple documents
- Calls InsertOne for a single document or InsertMany for multiple documents
- The documents are added to the collection with auto-generated ObjectIds if not provided
Requirements
- Either a valid client ID from Connect node OR database credentials
- Valid database name (non-empty)
- Valid collection name (non-empty)
- Valid JSON document(s) in the MongoDB Query field
- Appropriate permissions to insert documents in the collection
Error Handling
The node will return specific errors in the following cases:
- ErrInvalidArg - Database name or collection name is empty, or client/credentials are invalid
- ErrConnection - Cannot connect to MongoDB (when using credentials)
- JSON parsing errors if the document format is invalid
- Duplicate key errors if a document with the same unique index value exists
- Schema validation errors if the collection has validation rules
- Permission errors if the user doesn't have insert rights
Usage Notes
- The collection will be created automatically if it doesn't exist
- MongoDB automatically adds an
_idfield with a unique ObjectId if not provided - You can insert a single document (object) or multiple documents (array)
- The MongoDB Query field supports Handlebars templates for dynamic values
- Field values can be strings, numbers, booleans, arrays, nested objects, dates, etc.
- Large batch inserts are more efficient with the array format
- You can use either the client ID approach or direct credentials approach
Document Format
Single Document:
{
"name": "John Doe",
"email": "john@example.com",
"age": 30,
"active": true,
"tags": ["customer", "premium"]
}
Multiple Documents:
[
{
"name": "John Doe",
"email": "john@example.com"
},
{
"name": "Jane Smith",
"email": "jane@example.com"
},
{
"name": "Bob Johnson",
"email": "bob@example.com"
}
]
Handlebars Template Support
You can use Handlebars templates to insert dynamic values from the message context:
{
"name": "{{user_name}}",
"email": "{{user_email}}",
"timestamp": "{{current_time}}",
"status": "{{status}}"
}
Example Usage
Scenario 1: Insert a single user document
- Connect node → Client Id
- Insert Document:
- MongoDB Client Id: (from Connect)
- Database Name: "myapp"
- Collection Name: "users"
- MongoDB Query:
{
"username": "jdoe",
"email": "jdoe@example.com",
"created_at": "2024-01-15",
"role": "user"
}
Scenario 2: Insert multiple products
- Insert Document:
- Database Name: "ecommerce"
- Collection Name: "products"
- Credentials: (select credential)
- MongoDB Query:
[
{
"sku": "PROD-001",
"name": "Widget A",
"price": 19.99,
"stock": 100
},
{
"sku": "PROD-002",
"name": "Widget B",
"price": 24.99,
"stock": 50
}
]
Scenario 3: Insert with dynamic values using Handlebars
Set Variables:
- customer_name = "Alice Brown"
- order_total = 99.99
- order_date = "2024-01-15"
Insert Document:
- Database Name: "orders"
- Collection Name: "sales"
- MongoDB Query:
{
"customer": "{{customer_name}}",
"total": {{order_total}},
"date": "{{order_date}}",
"status": "pending"
}
Scenario 4: Insert data from external source
HTTP Request → response
For Each item in response.data:
Insert Document:
- Database Name: "sync"
- Collection Name: "items"
- MongoDB Query:
{
"external_id": "{{item.id}}",
"name": "{{item.name}}",
"value": {{item.value}},
"synced_at": "{{current_timestamp}}"
}
Scenario 5: Bulk insert from CSV
Read CSV → csv_data
Set Variable:
- documents = csv_data.map(row => ({
"product_id": row.id,
"product_name": row.name,
"category": row.category,
"price": parseFloat(row.price)
}))
Insert Document:
- Database Name: "inventory"
- Collection Name: "products"
- MongoDB Query: {documents}
Common Use Cases
- User Registration: Store new user accounts
- Data Migration: Transfer data from other systems to MongoDB
- Logging: Insert activity logs or audit trails
- IoT Data: Store sensor readings or device data
- Form Submissions: Save form data from web applications
- Bulk Import: Import large datasets from CSV, Excel, or APIs
- Archival: Store historical records for long-term retention
Best Practices
- Validate data before insertion to prevent bad data
- Use batch inserts (arrays) for better performance with multiple documents
- Include timestamps for audit purposes
- Design your document schema before inserting
- Use meaningful field names that follow a consistent naming convention
- Consider creating indexes on frequently queried fields
- Handle errors appropriately to prevent data loss
- Use transactions for related inserts that should succeed or fail together
Common Errors
Empty Database Name:
- Cause: Database name input is empty
- Solution: Provide a valid database name
Empty Collection Name:
- Cause: Collection name input is empty
- Solution: Provide a valid collection name
Invalid JSON:
- Cause: MongoDB Query field contains malformed JSON
- Solution: Validate your JSON syntax using a JSON validator
Duplicate Key Error:
- Cause: Attempting to insert a document with a duplicate value for a unique index
- Solution: Check for existing documents or use update operations instead
Document Too Large:
- Cause: Document exceeds MongoDB's 16MB size limit
- Solution: Reduce document size or store large data externally
Schema Validation Failed:
- Cause: Document doesn't match the collection's validation rules
- Solution: Ensure document structure matches the schema requirements
Related Nodes
- Update Document - Modify existing documents
- Delete Document - Remove documents from collection
- Read Document - Query and retrieve documents
- Read All - Retrieve all documents from a collection