Describe the problem/error/question
I’m encountering an issue when using the MongoDB node in n8n to find documents where a field contains an ObjectId inside an array.
I have a collection called pros, and each document has a field campaigns, which is an array of ObjectIds.
In MongoDB Compass, I can query successfully using:
{ campaigns: ObjectId("67613823f92d1c8271bbafee") }
However, when I attempt a similar query in n8n, I don’t get any results.
What works for a simple (non-array) field:
I found this format on the forum to search for a campaigns field that directly contains an ObjectId (and not an array). This query works:
{ "$expr": { "$eq": ["$campaigns", { "$toObjectId": "{{ $json.campaignId }}" }] } }
But as soon as I try to search within an array of ObjectIds, it doesn’t work.
What I tried:
- Query with
$in:
{ "campaigns": { "$in": [ "{{ $json.campaignId }}" ] } }
Result:
The MongoDB node outputs an empty array:
[{}]
- Query with
$exprinside$in:
{
"campaigns": {
"$in": [
{ "$expr": { "$eq": ["$campaigns", { "$toObjectId": "{{ $json.campaignId }}" }] } }
]
}
}
Result:
cannot nest $ under $in
Example of a document in my pros collection:
{
"_id": ObjectId("64f5a1c2e4b0a8f7654a9cde"),
"name": "John Doe",
"campaigns": [
ObjectId("67613823f92d1c8271bbafee"),
ObjectId("1234567890abcdef12345678")
]
}
What is the error message (if any)?
- cannot nest
$under$in - Empty results when using other queries.
Please share your workflow
Here is a minimal example to reproduce the issue:
Share the output returned by the last node
Here is the output when running the workflow:
[
{}
]
Expected: Documents where the campaigns array contains the campaignId.
Information on your n8n setup
- n8n version: 1.72.1
- Database: SQLite
- n8n EXECUTIONS_PROCESS setting: Regular
- Running n8n via: npm
- Operating system: n8n Cloud
Thank you in advance for your help! ![]()
Guillaume.