Need to frame a find query based on a variable

I will get the CREATED_BY field for one scenerio and I am not receiving this for other scenerios. So
if I receive this field, I need to fetch the data which are created by this value( getting from CREATED_BY) else I need to fetch all the data.
I have tried below and it is not working
srQuery = createdBy?{“CREATED_BY":"x@y.com”}:“”;
mycollection.find({“ERROR_FLAG”: “E”, srQuery}).lean().sort({ “createdAt”: -1 }))

One way is to use an $expr and $or condition to check if it’s either blank or the value you set?

var theVarable = 'john';
db.getCollection('Test').find({
    $expr:{
        $or:[
            {$eq:['$name', theVarable]},
            {$eq:['', theVarable]}
        ]
    }
})

So I can set theVariable to either blank or ‘john’ and it’ll return a record, if you pass in ‘bob’ then it’ll fail and you get nothing.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.