Dynamic $or statements

Hello all,
I have a project where the database needs to be queried for at least one of a variable list of languages. I am accessing the MongoDB from node.js.

const cursor = client.db(<mydatabase>).collection(<collection>).find({
            "discipline": reqdiscipline,
             "available": availability,
             $or: [ { "language": reqlanguage[0] }, { "language" : reqlanguage[1]} ] 
             } ) ;

“discipline” has only one possible value from a list of choices
“available” is a boolean
“language” can have 1,2,3… possible values
Here I have it set up to take $or parameters from an array “language” with two elements which works fine. My problem is that there may be more or less elements in the array. Never zero elements. How can I dynamically create the $or query when the array “reqlanguage” has a diffent size each time I make the query. I tried it as a string with various parts escaped but didn’t have any success.
Thanks for any help, this should be the last hurdle in my project.

Hello @John_Parsons, welcome to the MongoDB Community forum!

You can use the $in query operator which takes an array of possible matching values for a field. For example:

language: { $in: INPUT_ARRAY }

Where the variable INPUT_ARRAY = [ "english", "french", ... ]

This is same as:

$or: [ { "language": "english" }, { "language" : "french" } ]

So, in your case you can use reqlanguage as shown below, since its an array already:

language: { $in: reqlanguage }

1 Like

Thank you, I had tried the $in in an earlier incarnation but then moved to the $or for some reason. This now works perfectly.

You mean the $in operator works fine now?

Sorry for the confusion.
Your suggestion
language: { $in: reqlanguage }
works perfectly

Thanks again.

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