Read Document
Queries and retrieves documents from a MongoDB collection based on a filter.
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 query.
- MongoDB Query - MongoDB query filter in JSON format to match documents. Only documents matching this filter will be returned.
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.
Output
- Document - An array of documents matching the query filter. Each document is returned as an object with all its fields.
How It Works
The Read Document node retrieves documents from a MongoDB collection based on a query filter. 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
- Accesses the specified collection
- Executes a Find operation with the provided filter
- Retrieves all matching documents
- Returns the documents as an array
Requirements
- Either a valid client ID from Connect node OR database credentials
- Valid database name (non-empty)
- Valid collection name (non-empty)
- Valid JSON query filter
- Appropriate permissions to read documents from 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 query filter format is invalid
- Permission errors if the user doesn't have read rights
- Collection not found errors if the collection doesn't exist
Usage Notes
- Returns an array of documents, even if only one or zero documents match
- An empty filter
{}returns all documents in the collection - The MongoDB Query field supports Handlebars templates for dynamic values
- Results include all document fields including the
_idfield - Large result sets are loaded entirely into memory
- You can use either the client ID approach or direct credentials approach
- For retrieving all documents without filtering, use the Read All node instead
Query Filter Format
The query filter uses MongoDB query syntax in JSON format:
Find by exact match:
{
"status": "active"
}
Find by multiple conditions:
{
"status": "active",
"age": {
"$gte": 18
}
}
Find by ID:
{
"_id": {
"$oid": "507f1f77bcf86cd799439011"
}
}
Find all documents:
{}
Example Usage
Scenario 1: Find users by status
- Connect node → Client Id
- Read Document:
- MongoDB Client Id: (from Connect)
- Database Name: "myapp"
- Collection Name: "users"
- MongoDB Query:
{
"status": "active"
} - Output: active_users
- Log: "Found " + active_users.length + " active users"
Scenario 2: Find products in price range
Read Document:
- Database Name: "ecommerce"
- Collection Name: "products"
- Credentials: (select credential)
- MongoDB Query:
{
"price": {
"$gte": 10,
"$lte": 50
},
"in_stock": true
}
- Output: affordable_products
For Each product in affordable_products:
Log: product.name + " - $" + product.price
Scenario 3: Find with dynamic values using Handlebars
Set Variable:
- user_email = "john@example.com"
Read Document:
- Database Name: "accounts"
- Collection Name: "users"
- MongoDB Query:
{
"email": "{{user_email}}"
}
- Output: user_data
If user_data.length > 0:
Log: "User found: " + user_data[0].name
Else:
Log: "User not found"
Scenario 4: Find orders by date range
Set Variables:
- start_date = "2024-01-01"
- end_date = "2024-01-31"
Read Document:
- Database Name: "sales"
- Collection Name: "orders"
- MongoDB Query:
{
"order_date": {
"$gte": "{{start_date}}",
"$lte": "{{end_date}}"
}
}
- Output: january_orders
Set Variable:
- total_revenue = january_orders.reduce((sum, order) => sum + order.total, 0)
Log: "January revenue: $" + total_revenue
Scenario 5: Find documents with array field matching
Read Document:
- Database Name: "blog"
- Collection Name: "posts"
- MongoDB Query:
{
"tags": {
"$in": ["mongodb", "database", "nosql"]
}
}
- Output: tech_posts
Scenario 6: Find using regular expression
Read Document:
- Database Name: "customers"
- Collection Name: "contacts"
- MongoDB Query:
{
"email": {
"$regex": "@gmail\\.com$",
"$options": "i"
}
}
- Output: gmail_users
Scenario 7: Complex query with logical operators
Read Document:
- Database Name: "inventory"
- Collection Name: "products"
- MongoDB Query:
{
"$or": [
{
"category": "electronics",
"price": { "$lt": 100 }
},
{
"category": "books",
"discount": { "$gt": 20 }
}
]
}
- Output: deals
Common Use Cases
- Data Retrieval: Fetch specific records based on criteria
- User Lookup: Find user accounts by email, username, or other identifiers
- Search Functionality: Implement search features in applications
- Reporting: Query data for reports and analytics
- Validation: Check if documents exist before operations
- Data Export: Retrieve data for export to other systems
- Filtering: Get subsets of data based on conditions
MongoDB Query Operators
Common operators you can use in the query filter:
- $eq - Equal to (implicit when using field: value)
- $ne - Not equal to
- $gt - Greater than
- $gte - Greater than or equal to
- $lt - Less than
- $lte - Less than or equal to
- $in - Matches any value in an array
- $nin - Matches none of the values in an array
- $and - Logical AND
- $or - Logical OR
- $not - Logical NOT
- $nor - Logical NOR
- $exists - Field exists
- $type - Field is of specified type
- $regex - Regular expression match
- $elemMatch - Array element matches all conditions
- $size - Array has specified size
Working with Results
Access first document:
const firstDoc = documents[0];
Check if results exist:
if (documents.length > 0) {
// Process documents
}
Iterate through results:
documents.forEach(doc => {
console.log(doc.name);
});
Extract specific fields:
const names = documents.map(doc => doc.name);
Filter results further:
const filtered = documents.filter(doc => doc.age > 30);
Best Practices
- Use specific query filters to limit the number of returned documents
- Create indexes on frequently queried fields for better performance
- Consider pagination for large result sets
- Test queries with small datasets first
- Use projection (field selection) when you don't need all fields
- Monitor query performance and optimize as needed
- Handle empty result arrays appropriately in your flows
- Use Read All node when you need all documents without filtering
Performance Tips
- Index fields used in query filters
- Limit result sets when possible
- Use covered queries (queries that can be satisfied using indexes alone)
- Avoid regular expressions on large collections without indexes
- Consider using aggregation pipeline for complex queries
- Monitor slow queries and optimize
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 Query JSON:
- Cause: MongoDB Query field contains malformed JSON
- Solution: Validate your JSON syntax using a JSON validator
Collection Not Found:
- Cause: Specified collection doesn't exist
- Solution: Verify collection name or create the collection first
Permission Denied:
- Cause: User doesn't have read permission
- Solution: Ensure user has read or readWrite role
Invalid Query Operator:
- Cause: Using incorrect or non-existent query operator
- Solution: Use valid MongoDB query operators
Related Nodes
- Read All - Retrieve all documents without filtering
- Insert Document - Add new documents
- Update Document - Modify documents based on filter
- Delete Document - Remove documents based on filter