I am working on MongoDB and next js project. I want to apply filter on products. There are multiple filters. I want to include a filter in and operator only if value of a variable is not empty or undefined I want something like this that works
Product.find({
$and:[
{ tag : { $in : preferences,},
{$cond:{
if: { $ne: ['$allergens'], []],},
then: {
allergens: {$in :allergens },
if:{ $ne: ['$type'],''],},
then: {
type: type ,
}
}
})
}]
What would be the correct way of doing this? Thanks
CodePudding user response:
Check the correct syntax:
{ $and: [ { Expression1 }, { Expression2 }, ..., { ExpressionN } ] }
or
{ { Expression1 }, { Expression2 }, ..., { ExpressionN }}
CodePudding user response:
This should work. The trick is to use $cond plus $ifNull to see if the field is unset.
var r = [
{ tag: [ "A","B"], allergens: ["pollen","badJokes"], type: "foo" },
{ tag: [ "B","C"], type: "foo" },
{ tag: [ "C","D"], allergens: ["other"] },
{ tag: [ "E","D"], allergens: ["corn"] }
];
db.foo.drop();
db.foo.insert(r);
var tags = [ "C","A" ];
var type = 'foo';
var allergens = ['pollen','corn'];
c = db.foo.aggregate([
{$match: {$expr: {$and: [
{$ne:[ [], {$setIntersection: [ "$tag", tags ]} ] },
{$cond: {
if: {$eq:["$type", {$ifNull:["$type",null]} ]},
then: {$eq:["$type",type]},
else: true
}},
{$cond: {
if: {$eq:["$allergens", {$ifNull:["$allergens",null]} ]},
then: {$gt:[{$size: {$setIntersection: [ "$allergens", allergens ]}} , 0 ]},
else: true
}}
]}
}}
]);
