Queries - Dynamically construct queries

Hello,

I have this data in a table:

I want to do a query that gives me all the “channels” that contain #240# and #7556# and #2892#

This code works:

    const first = new Moralis.Query(Terminal);
    first.contains("channel", "#240#");

    const second = new Moralis.Query(Terminal);
    second.contains("channel", "#7556#");

    const third = new Moralis.Query(Terminal);
    third.contains("channel", "#2892#");

    const mainQuery = Moralis.Query.or(first, second, third);

The issue I have is that I have the channels in an array like:

    let channelIds = [ "#240#", "#2892#", "#7556#" ];

and so I want to dynamically construct the queries above

How can I do that?

I tried:

    let channelIds = [ "#240#", "#2892#", "#7556#" ];
    let queries = [];

    channelIds.forEach(item => {
        const query = new Moralis.Query(Terminal).contains("channel", item);
        queries.push(query);
    })

    const mainQuery = new Moralis.Query.or(queries);
    mainQuery.limit(chatLimit);

This doesn’t work. Is there any way to do it?

1 Like

Hey @Chriton

You can use Aggregate Match
Example:

Moralis.Cloud.define("task", async (request) => {
  const query = new Moralis.Query("Terminal");

  const pipeline = [
    { match: { channel: { $in: [ "#240#", "#2892#", "#7556#" ]} } },
  ];

  const result = await query.aggregate(pipeline, { useMasterKey: true });
  return result;
});

Hey, thanks, trying it now