MongoDB: Dynamic collection

A situation may arise when from the same Database, we might need to create the same queries using different collections. So to save time, now you can simply create a single query and use the collection name dynamically. So let’s see how it can be done.

Setup MongoDB Connector

First we need to configure our MongoDB connector. Refer here to see how it’s done. We are assuming your MongoDB database consists of multiple collections.

Configure Dropdown control

  • Drag and place a dropdown control.
  • In options, we provide two or more collections from our database.
  • Go to Dropdown > data > options > Data and there paste collection names in an array
  • Eg :- [“users”,”clients”]

  • Now go to Dropdown > data > Selected-option > Data and give a default value, lets keep it [“users”]

Create Query

  • Now select your MongoDB connector created from Connectors option and click on a + ADD QUERY

  • Now name your query accordingly, here we’re naming it as Get_data. From the collections dropdown, select the {{CollectionName}} option.
  • On the right hand side, you can notice the variable value field is visible now, try entering your collection name and click test the query

  • After successfully testing collection, save it

Note- Dynamic collection option will only work properly ONLY IF schemas both the database is exactly same. This is in case you are using data for tablegrid control. For other applications, it will work fine, like in case you simply need the data to process for some other control.

Configure Tablegrid control

  • Drag and place a tablegrid control. Select Data > connectors.
  • Select MongoDB connector > Get_data query. Click on Continue

  • Now while in final steps, for collectionName variable, select Dropdown control from Keywords

  • Select Columns to bind and save it.

  • Finally
    Save
    the query.

You can also use the same query for some particular collection in the same database as well. All you need to do is that, while configuring the connector, provide the other collection’s name.

Preview after successful configuration

Data being fetched using Users database

Data being fetched using clients database