Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

417
Views
How to use Mongodb if condition in $and operator

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Check the correct syntax:

{ $and: [ { Expression1 }, { Expression2 }, ..., { ExpressionN } ] }
or
{ { Expression1 }, { Expression2 }, ..., { ExpressionN }}
about 4 years ago · Juan Pablo Isaza Report

0

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
        }}
    ]}
             }}
]);

Alternatively, it might be easier to construct the $and expression programmatically outside of the query:

// Init the and expression array with tags since we always want that:                                                                               
var andExpr = [ {$ne:[ [], {$setIntersection: [ "$tag", tags ]} ] } ];

if(type != undefined) {
    andExpr.push({$eq:["$type",type]});
}
if(allergens != undefined) {
    // Use $ifNull to defend against missing field since
    // $size on a null field will fail, not yield 0:
    andExpr.push({$gt:[{$size: {$setIntersection: [ {$ifNull:["$allergens",[]]}, allergens ]}} , 0 ]});
}

c = db.foo.aggregate([
    {$match: {$expr: {$and: andExpr}} }
]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!