I am trying to search a MongoDB database filtering on a specific data item. Specifically, I want USA = PG-13 for my filter.
How to make a request: to get movies, where MPAA for USA = PG-13?
collection country:
{
"_id": ObjectId("4fd79ec34c9fda9d05000080"),
"en": "USA"
}
{
"_id": ObjectId("4fd79ec34c9fda9d0500007f"),
"en": "Hong Kong"
}
collection movie:
{
"_id": ObjectId("4fd79ec34c9fda9d05000081"),
"movieId": {
"imdb": "0848228"
},
"movieTitle": "The Avengers",
"movieYearSpan": {
"start": "2012",
"end": "2012"
},
"movieType": "Movie",
"movieMpaa": {
"verdict": "Rated PG-13",
"0": {
"mpaa": "IIA",
"country": ObjectId("4fd79ec34c9fda9d0500007f")
},
"1": {
"mpaa": "PG-13",
"country": ObjectId("4fd79ec34c9fda9d05000080")
}
}
}
I tried to first get the ID for the USA.
$cursorCountry = $collectionCountry->find(array("en" => "USA"));
$idCountry = $cursorCountry->getNext();
$_id = $idCountry["_id"];
$cursorMovie = $collectionMovie->find(array("movieMpaa.country" => $_id, "movieMpaa.mpaa" => "PG-13"));
Does not work!
How then to make a request?
To get movies, where MPAA for USA = PG-13?
As your data is laid out, there is no good query here.
If you can change your
moviescollection to the following, then your query will work:When
movieMpaa.countriesis an array of objects, then you can query into that array formovieMpaa.countries.country. MongoDB will recognize the array and “drill into” the objects.However, there is another way structure this that probably much easier longer term:
If a country can only have one rating, then technically that
countriesvalue is a dictionary ofCountries => ratings. The structure above stores them this way.However, the use of
ObjectIdis a little ugly there. Note that you can override the ID in thecountrycollection. Consider using the 2 or 3-character ISO codes instead. These are easier to read.