Home > Back-end >  Querying a collection for any documents that match any values listed in an array?
Querying a collection for any documents that match any values listed in an array?

Time:10-08

I currently have a collection Raffle where each document contains a raffle_id and user_id. This collection serves to contain a raffle ticket that a user has purchased, therefore there could be multiple tickets per user for many different raffles. I have queried this collection to return all occurrences of the raffle_id matching a specific id that I've passed in, therefore if I have 10 different raffles and I hypothetically queried for only the tickets that belong to the "Win a brand new necklace" raffle, I would only receive these respective entries (not tickets that belong to "Win a brand new car"). The array contains the id's of the users.

e.g:

myArr[0] = "104abc191";
myArr[1] = "134gkd131";
...
myArr[n] = "404fdc259";

Since this array contains distinct users that have entered a specific raffle, its size could be either extremely large, extremely small, or somewhere inbetween.

Since I have only an array of strings that represent the user id's, I want to be able to query my User collection based on these id's to find additional information on the user (email, phone, etc.). How would I query a collection for any documents that match any id's in my array?

I thought of doing something similar to the following:

User.find({ $or: [{ "id": myArr[0] }, { "id": myArr[1] }, ..., { "id": myArr[n] });

I'm unsure if I can include more than 2 criteria in the $or array (I'd assume yes), however this doesn't seem to be very practical given that my search criteria could be very large depending on how many distinct users have entered this specific raffle.

Am I able to query a collection with something along the lines of "If collection contains any documents that has a matching id with any values in a given array, add them into the array to be returned"?

CodePudding user response:

How about $in (https://docs.mongodb.com/manual/reference/operator/query/in/)

User.find({ id: { $in: myArr }});
  • Related