1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That doesn't seem to be working for me (I also tried $gt: 0), it just gives "Network Error at createError" As for the $arrayElemAt suggestion, I tried the following, but it didn't work either: { [arrayName]: { $arrayElemAt: [ [0], { $exists: true } ] } }
I updated my answer. $size doesn't work with $gt or any comparisons for some reason. We have to use an aggregate then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.