Search code examples
javascriptnode.jsmongodbmongoose

MongoDB, Mongoose Find if Array Contains/Includes


Basically let's say that I need to find an element by multiple unique names that are stored in an string array type. [String]

const ExampleSchema = new Schema({
  names: [String],
  etc...
});

I have a string that is included in this array of a document and I wanna find the document using this unique string. Is this even possible?

Something like $contains ($contains does not exist in mongoose, I just copied how $in works)

ExampleModel.find({{ "names": { "$contains": my_unique_string } });

Solution

  • You can try $in with $expr, it can allow to check string is in names array or not,

    ExampleModel.find({
      $expr: {
        $in: [my_unique_string, "$names"]
      }
    })
    

    Playground