Home > Enterprise >  mongoose — Array variable in query
mongoose — Array variable in query

Time:04-06

I'm trying to write a mongoose query that allows me to find a document with a populated array, where the name of the array is stored in a variable. I've tried various syntaxes, using [square brackets], etc, and I've searched but can't find anything that works.

var arrayName = req.params.abbreviation   "Films";
console.log(arrayName); //documentaryFilms

FilmModel.findOne({
  $and: [
    { incomplete: false },
    { [arrayName].[0]: { $exists: true } }
...

Does anyone know how this can be achieved? Thank you

CodePudding user response:

Use the $size operator to get the length of the array.

FilmModel.aggregate(
[
     {
       $addFields: {
        "size_of_array": {
          $size: "$abcFilms"
        }
       }
     }
     { 
       $match: { "size_of_array": { $gt: 0 } } 
     }
])

If you want to filter based on an element with index n in an array take a look at $arrayElemAt operator.

  • Related