I want to fetch all documents from a collection where a document property has the value of an array element.
For instance, I have a collection where all documents have a property named ".foreignKey" and I want to find all documents where .foreignKey matches one of the elements of an array named "foreignKeys".
The code that I have currently have looks like this:
const foreignKeys = [0,10,100,500]
const result = await getAppDatabase().collection("Collection")).find({
foreignKey: foreignKeys
}).toArray()
Result must have documents where .foreignKey is either 0, 10, 100 or 500.
The code that I've provided does not work and I cannot seem to find an efficient solution to my problem. Thanks a lot for any help.
CodePudding user response:
You could use $in
or $or
Recommendation is $in
for your case
When using $or with that are equality checks for the value of the same field, use the $in operator instead of the $or operator.
await getAppDatabase().collection("Collection")).find({
".foreignKey": { "$in": foreignKeys}}).toArray()