2

In my synfony 2 project, I'm filtering search results using a query builder. In my MongoDB i have some values in an array.

Query Bulider has the "in" operator that allows to query for values that equal one of many in an array. I wanted to perform the opposite operation, i.e. given a single value, query for entries in the data base that contain an array, that contains my value.

For instance, say I have this entry in my MongoDB:

{
  "_id": 123,
  "name": "John",
  "countries_visited":
  [
    "Australia"
    "Bulgaria",
    "Canada"
  ]
}

And I want to query my database for persons who have visited "Canada". Right now, I'm using the where attribute as follows, but I'm looking for a better way to do this.

        $qb->field('countries_visited')->where("function(){
            return this.indexOf(".$countryName.") > -1
        }");

edit: The in and notIn operator receives an array as parameter and compares it against a single value in MongoDB. I need to provide a single parameter and apply it to an array field in MongoDB, hence "inverse in". I guess I need a contains operator if there's such a thing.

ecc
  • 1,490
  • 1
  • 17
  • 42

1 Answers1

2

Interesting, MongoDB takes care of this automatically. If querying for a single value against an array field, Mongo will assume you want the check the array if it contains the value.

Taken from the docs:

Match an Array Element

Equality matches can specify a single element in the array to match. These specifications match if the array contains at least one element with the specified value.

So you should be able to do

$users = $dm->getRepository('User')->findOneBy([
    'countries_visited' => 'Canada'
]);

or

$qb->field('countries_visited')->equals('Canada');
Community
  • 1
  • 1
Adam Elsodaney
  • 7,722
  • 6
  • 39
  • 65
  • Equals operator will work in an array? Will try and bring back results. Thanks. – ecc Oct 07 '14 at 15:42
  • 1
    It totally does. As a side note, this will only travel arrays by one level and won't work with arrays inside arrays. – ecc Oct 07 '14 at 15:47