below is my query: while executing below query getting mongoerror : Expression $in takes exactly 2 arguments. 1 were passed in. i am using $in Comparison operator
{ "$expr": { "$not": { "$eq":{ "$and": [ { "PrName": { "$in": [ "pname" ] } }, { "AccountId": { "$in": [ "34562", "88765", "87654", "12345" ] } } ] } } } }
2 Answers
When you use $expr
, the operator expressions syntax changes a little:
{ $in: [ <expression>, <array expression> ] }
{
"$expr": {
"$not": {
"$and": [
{
"$in": [
"$PrName",
[
"pname"
]
]
},
{
"$in": [
"$AccountId",
[
"34562",
"88765",
"87654",
"12345"
]
]
}
]
}
}
}
In my case, I had used aggregate
function and multiple $lookup
and pipeline
.
Example: At first was getting a product with slug, all product have keywords[]
.
I had to get related products that have at least one matching keywords.
My related_products looked like:
{
$lookup: {
from: "Products",
let: {
// ...
productKeywords: { $arrayElemAt: ["$product.keywords", 0] }
},
pipeline: [
{
$match: {
$expr: {
$and: [
// ...
{ $ne: ["$slug", slug] },
{ $or: [
// ... more conditions like same category, etc.
{ keywords: { $in: "$$productKeywords" } }
] }
]
}
}
}
],
},
as: "related_products"
},
I was getting this error and I knew $in
in $expr
works differently. When I changed it to { $in: ["$keywords", "$$productKeywords"] }
, it was not giving any product by matching keywords though there were many products.
After searching all online, I can't find the solution.
Finally after many hours of searching and thinking, something new idea came on my mind. If I perform intersection on keywords with productKeywords and if the result keyword size is one or larger, it means there is matching keyword . If the keywords match, it is the related product.
I just replaced $in
with below line.
{ $gt: [{ $size: { $setIntersection: ["$keywords", "$$productKeywords"] } }, 0] }
This is working on my case as I have expected.