Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

413
Vistas
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 Respuestas
Responde la pregunta

0

Check the correct syntax:

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

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda