Creating a query for mongodb

Viewed 46

defined variables :

    let min_cost = '';
    let status   = '';
    let min_rent = '';
    let filter = {};

I have a structure below $and: [] and it has three objects as defined below, Here I am trying to insert those three objects one by one only if the payload contains their values. For Ex.: if min_cost !== '', then the first object should be pushed into $and : [] and same with the status and min_rent, Then finally inserting $and : [] into filter object.

{
       $and: [
            {
                $and: [
                    { "data.label": "Total Cost" },
                    {
                        "data.value": {
                            "$gte": min_cost
                        }
                    }
                ],
            },
            {
                $and: [
                    { "data.label": "Possession Status" },
                    { "data.value": status }
                ],

            },
            {
                $and: [
                    { "data.label": "Estimated Monthly Rent" },
                    {
                        "data.value": {
                            "$gte": min_rent
                        }
                    }
                ],
            },

        ]
}

final output :

db.collection.aggregate([
{
  "$match": filter
}
])

Thanks in advance!

1 Answers

check if condition and push $and object to filter array and after all conditions put $and with filter array in $match stage.

let min_cost = '';
let status   = '';
let min_rent = '';
let filter = [];

if (min_cost) {
    filter.push({
        $and: [
            { "data.label": "Total Cost" },
            { "data.value": { "$gte": min_cost } }
        ]
    });
}

if (status) {
    filter.push({
        $and: [
            { "data.label": "Possession Status" },
            { "data.value": status }
        ]
    });
}

if (min_rent) {
    filter.push({
        $and: [
            { "data.label": "Estimated Monthly Rent" },
            { "data.value": { "$gte": min_rent } }
        ]
    });
}

db.collection.aggregate([
    {  "$match": filter.length ? { $and: filter } : {} }
])
Related