Home > other >  Conditionally add filter predicaments before returning data in Mongodb
Conditionally add filter predicaments before returning data in Mongodb

Time:10-11

since I cant word properly what I am trying to achieve as many topics can mistakenly fall under the terminology of conditionally filtering mongodb query. Here is what I want to achieve,

I have a users DB, I am trying to send a search query to my backend with the following data {"country":"all","category":"all","gender":"all","ageRange":[25, 40]}

And I am trying to add these parameters into my query programatically. Eg,

const search = db.collection("users").find();

if (params.country == "ALL") {
    search.addFilter( { country: "..." } )
}

if (params.age < 18) {
    search.addFilter( { minor : true } )
}

const data = search.limit(30).toArray();

Is something like this possible? As when country is equal to "all" I dont want to apply any filter but if country is equal to some country I want to apply that country as the filter and so on. Can I programatically add to the filter predicament?

Using Nodejs (Nextjs api), so javascript and mongodb library

CodePudding user response:

var filters = {}
var andObj = []
if (params.country == "ALL") {
    andObj.push( { country: {$regex:".*." }} )
}

if (params.age < 18) {
   andObj.push( { minor : true } )
}
filters['$and'] = andObj
const data = await db.collection("users").find(filters).limit(30).toArray();

or

var filters = {}
var andObj = []
if (params.country != "ALL") {
    andObj.push( { country: params.country} )
}

if (params.age < 18) {
   andObj.push( { minor : true } )
}
filters['$and'] = andObj
const data = await db.collection("users").find(filters).limit(30).toArray();
  • Related