Overview
This node allows executing native MongoDB queries directly on a specified collection with support for complex query structures, including date and ObjectId types. It supports three operations: finding multiple documents, finding a single document, and running aggregation pipelines. This flexibility makes it ideal for scenarios where users need to perform advanced data retrieval or aggregation in MongoDB without writing custom code outside n8n.
Practical examples:
- Retrieve the latest 10 orders from an "orders" collection filtered by a date range.
- Find a single user document by its unique ObjectId.
- Run an aggregation pipeline to group sales data by region and calculate totals.
Properties
| Name | Meaning |
|---|---|
| Collection | The name of the MongoDB collection to query. |
| Query | The MongoDB query in JSON format. Supports special $date for ISO date strings and $oid for ObjectIds. This defines the filter or aggregation pipeline depending on the operation. |
| Max Results | The maximum number of documents to return (applies to "find" and "aggregate" operations). |
Output
The node outputs an array of JSON objects with the following structure:
result: The query result, which can be:- An array of documents (for "find" and "aggregate").
- A single document object (for "findOne").
query: The parsed query or aggregation pipeline used.operation: The operation performed ("find", "findOne", or "aggregate").collection: The name of the collection queried.
If an error occurs and the node is set to continue on failure, the output will contain an error field with the error message instead of result.
Dates in the output are converted to ISO string format for readability.
Dependencies
- Requires a valid MongoDB connection string and optionally a database name.
- Needs credentials that provide access to the MongoDB instance.
- Uses the official MongoDB Node.js driver internally.
Troubleshooting
- Invalid JSON in Query: If the query string is not valid JSON, the node will throw an "Invalid JSON" error. Ensure the query is properly formatted JSON, using double quotes and correct syntax.
- Database Name Not Found: If no database is specified in credentials or connection string, the node will throw an error indicating the database name could not be found. Make sure the connection string includes the database or specify it in credentials.
- Unknown Operation: If an unsupported operation is selected, an error will be thrown. Use only "find", "findOne", or "aggregate".
- Connection Errors: If the connection string or credentials are incorrect, connection attempts will fail. Verify credentials and network access.
- Query Parsing Errors: Special
$dateand$oidfields must be correctly formatted; otherwise, parsing will fail.