0

I have a collection that contains documents that are structured like this:

{
   "title": "some title",
   "participants": [1,2,3],
   "questions": ["question1", "question2", "question3"]
}

I would like to write a query that will allow me to select all documents that have more than 4 elements in the participants array and more than 3 elements in the questions array. I was able to run the following query:

db.myCollection.find({
        "$where": "this.questions.length > 3", 
        "$where": "this.participants.length > 4"}
).pretty()

But it is only applying the last $where condition (so documents where there is only 1 question are still being returned). How can I apply multiple conditionals based on array length to my query?

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486

1 Answers1

2

You can use the dot notation to check if a specific index exists like:

db.myCollection.find({
        "questions.3" : {$exists : true}, 
        "participants.4" : {$exists : true}}
)

which is equivalent to "find documents where questions.size() > 3and participants.size() > 4".

This approach was suggested by JohnyHK here (second answer)

Community
  • 1
  • 1
Anand Jayabalan
  • 12,294
  • 5
  • 41
  • 52