How to push the key and values to array and build the dynamic query?

I needs to build the query object for mongodb. while tired this I got the output like this,

output

{"$match":{"$and":[{id:1},{name:"Alfred"},{location:"moon"},{"values":{"$in":[{name:"u",age: 9}]} }]}}

this my code,

const queryFormat = (payload) => {
    delete payload.userEventId
    var query = {}
     var res = []
    for(key in payload) {
        if(typeof(payload[key])) {
       res.push({ [key]: payload[key] })
        }
        else {
            res.push({"$in" :{ [key]: payload[key] }})
        }
    }
    console.log(res[3])
    query['$match'] = {"$and" :res}
    console.log(query)    
}


const payload = {
    id :1,
    name : 'Alfred',
    location : 'moon',
    values : [{name: 'u',age:9}]
}
queryFormat(payload)

expected output

{"$match":{"$and":[{id:1},{name:"Alfred"},{location:"moon"},{"values":{"$in":[{name:"u"},{age: 9}]} }]}}

Thanks!

38 thoughts on “How to push the key and values to array and build the dynamic query?”

  1. You need to check is key array or not, if its array then loop and make new array for inner condition, try running below codesnippet,

    const queryFormat = (payload) => {
        let query = [];
        // LOOP OBJECT
        for(let key in payload) {
           // IS ARRAY? YES
           if(!Array.isArray(payload[key])) {
              query.push({ [key]: payload[key] });
           }
           // NO 
           else {
              let subQuery = [];
              // LOOP ARRAY
              for(let skey in payload[key]) {
                // LOOP OBJECT
                for(let okey in payload[key][skey]) {
                  subQuery.push({ [okey]: payload[key][skey][okey] });
                }
              }
              // BIND SUB QUERY
              query.push({ [key]: { "$in": subQuery } });
           }
        }
        // RETURN MATCH QUERY
        return { '$match': query }
    }
    
    const payload = {
        id :1,
        name : 'Alfred',
        location : 'moon',
        values : [{name: 'u',age:9}]
    }
    
    let result = queryFormat(payload);
    console.log(result);
    Reply

Leave a Comment