How do I filter a MongoDB collection using an OR for the values of a field using the NodeJS driver?

646 views Asked by At

I want to filter a collection if a specific field equals one value OR another. In the example below, I would like it to filter the collection if "field" is equal to either "option 1", "option 2" or "option 3". I'm using the NodeJS driver. Here's an example:

 await db
  .collection("collection_name")
  .find({ field: "option 1", "option 2", "option 3" }) // this is the crux
  .sort({ value: 1 })
  .limit(1)
  .toArray();
1

There are 1 answers

0
abondoa On BEST ANSWER

Most straight-forward would be to use the $in operator:

await db
 .collection("collection_name")
 .find({ field: {$in: ["option 1", "option 2", "option 3"]} }) // this is the fix
 .sort({ value: 1 })
 .limit(1)
 .toArray();

Documentation for the $in operator: https://docs.mongodb.com/manual/reference/operator/query/in/

Alternative, if you want to use the $or operator:

await db
 .collection("collection_name")
 .find({ $or: [{field:  "option 1"}, {field:  "option 2"}, {field:  "option 3"}] }) // this is the fix
 .sort({ value: 1 })
 .limit(1)
 .toArray();

Documentation for $or: https://docs.mongodb.com/manual/reference/operator/query/or/