Three common use cases for array-related searches:

I) See if a search term is in an array; e.g. is “mouse” in “animals”: [“cat”, “dog”, “mouse”]

II) See if a field is contained within an array (i.e. the opposite of the previous); e.g. does [1, 4, 7] contain “my_number”: 3

III) See if all items in an array search term are within in array field; e.g. are all the values of [“alpha”, “bravo”, “charlie”] within the field array “callsigns”: [“alpha”, “bravo”, “charlie”, “delta”]

For case (I), all you need to do is provide the term; mongo will figure out the array part. So you’d writedb.zoo.find( { animals: "mouse" } ).

For case (II), you use the “in” keyword: db.numbers.find( { my_number: { $in: [1, 4, 7] } } ).

For case (III), you use the “all” keyword: db.victory.find( { callsigns: { $all: ["alpha", "bravo", "charlie"] } } ).

To summarize:

  • To find a search term within an array, use standard search notation.
  • To match an array of search terms against a field, use in.
  • To compare all items in an array of search terms against an array field, use all.

Written by

Software engineer and renaissance man. I love the human side of computing.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store