dthree
dthree

Reputation: 20750

Match Meteor collection based on array of values

Suppose I have a list of IDs I want to filter a Collection by:

const ids = [1, 2, 3, 4];

How do I filter the collection to match just those IDs? Something like this doesn't work:

return Coll.fetch({_id: {$all: ids}});

Upvotes: 0

Views: 194

Answers (2)

Mostafiz Rahman
Mostafiz Rahman

Reputation: 8522

This will work:

return Collection.find({_id: {$in: ids}}).fetch();

Upvotes: 2

mutdmour
mutdmour

Reputation: 543

Here's how I might approach this:

function hasAllIds(collections, ids) {
  for (let i = 0; i < collections.length; i++) {
    let count = collections[i].find({
      _id: {
        $in: ids
      }
    }).count();
    if (count === ids.length) {
      return collections[i];
    }
  }
  return null;
}

const colls = [Meteor.users, Games]; //etc.
const ids = [1, 2, 3];
const coll = hasAllIds(colls, ids);
if (coll) {
  coll.find(); //or whatever
}

Upvotes: 0

Related Questions