Storing queries in document and evaluate using parameters

Hi can we store mongo db queries in mongo db document and later evaluate them with parameters? Currently it doesn’t work. Please see the details in this link.

Basically a document will have a query and I want to find the result of that query by giving parameters at run time in aggregation.

It should not be too hard to implement something along the lines:

Query stored somewhere with placeholders. The placeholders are string that starts with @.

stored_pipeline = [
    { "$match" : { 
        "creation_date" : "@creation_date" ,
        "user_id" : "@user_id" ,
        "status" : "vacation"
    } } 

The you setup a map for your place holders using the current values you wish.

query_map = {
    "@creation_date" : new Date( "2022-12-25" ) ,
    "@user_id" : "steevej"
}

Then you write a function that takes the stored query and the query map. This function goes over the stored query and replace each instance of a place holder with the current value from the query map.

function map_dynamic_query( stored_query , query_map )
{
   for stored_value in stored_query
   {
       if stored_value starts with @
       {
           dynamic_value = query_map.find( stored_value )
           replace stored_value with dynamic_value
       }
   }
}

Running the above function with the above stored_pipeline and query_map would produce an executable query such as:

stored_pipeline = [
    { "$match" : { 
        "creation_date" : 2022-12-25T00:00:00.0Z ,
        "user_id" : "steevej" ,
        "status" : "vacation"
    } } 
1 Like

@VIPAN_KUMAR, please share the final approach you took so that others find the forum useful.

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