Search through several collections -> result in one array

Hey everyone, I want to search through several collections on Mongo Realm and output the result in an array. I used the following function:

exports = function(amounts, colls){
  
  const query = { "amount": { $all: amounts } };
  const projection = { "name": 1 };
  
  // Accessing a mongodb service:
  var db = context.services.get("mongodb-atlas").db("App");
  
  var doc = [];

  var i;
  for(i of colls){
    doc.push(db.collection(i).find(query,projection).toArray());
  }

  // return the names 
  return doc;
};

With exports([“e”, “b”, “z”, “m”], [“CollA”, “CollB”]) in the console I get arrays in an array:

[
   [{"_id":{"$oid":"5f7b4ad6513f671c7e11a350"},"name":"Marmor"},
    {"_id":{"$oid":"5f7b4ae1513f671c7e11aa05"},"name":"Sand"}],

   [{"_id":{"$oid":"5f7b4aaa513f671c7e118bc3"},"name":"Kaese"},
    {"_id":{"$oid":"5f7b4ab7513f671c7e11922e"},"name":"Mandel"}]
]

How do I have to change the code to get only one array like below? So far all my attempts have failed.

[
   {"_id":{"$oid":"5f7b4ad6513f671c7e11a350"},"name":"Marmor"},
   {"_id":{"$oid":"5f7b4ae1513f671c7e11aa05"},"name":"Sand"},
   {"_id":{"$oid":"5f7b4aaa513f671c7e118bc3"},"name":"Kaese"},
   {"_id":{"$oid":"5f7b4ab7513f671c7e11922e"},"name":"Mandel"}
]

Any help on this one would be greatly appreciated.

Regards,
Axel

Hi @Axel_Ligon,

Have you tried using concat instead of push:

var i;
  for(i of colls){
    doc.concat(db.collection(i).find(query,projection).toArray());
  }

Best
Pavel

Yes, I did. I get a response in the console:
> result:

> result (JavaScript):
EJSON.parse(’’)

Hi @Axel_Ligon,

Sorry my mistake in the code. You will need to use an Async approach that worked for me:

exports = async function(amounts, colls){
  
  const query = { "amount": { $all: amounts } };
  const projection = { "name": 1 };
  
  // Accessing a mongodb service:
  var db = context.services.get("mongodb-atlas").db("App");
  
  var doc = [];

  var i;
  for(i of colls){
   doc = doc.concat(await db.collection(i).find(query,projection).toArray());
  }

  // return the names 
  return doc;
};

Thanks,
Pavel

1 Like

Test was successful. :grinning:
The combination of “async function(…)” and “doc = doc.concat(await …)” was the solution.

Thanks for your help.

1 Like

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