1

我正在尝试搜索对特定数据项进行筛选的 MongoDB 数据库。具体来说,我想要 USA = PG-13 作为我的过滤器。

如何提出请求:获取电影,其中美国 MPAA = PG-13?

采集国家:

{
   "_id": ObjectId("4fd79ec34c9fda9d05000080"),
   "en": "USA" 
}
{
   "_id": ObjectId("4fd79ec34c9fda9d0500007f"),
   "en": "Hong Kong" 
}

合集电影:

{
   "_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") 
    } 
  } 
}

我试图首先获得美国的身份证。

$cursorCountry = $collectionCountry->find(array("en" => "USA"));
$idCountry = $cursorCountry->getNext();
$_id = $idCountry["_id"];
$cursorMovie = $collectionMovie->find(array("movieMpaa.country" => $_id, "movieMpaa.mpaa" => "PG-13"));

不工作!那么如何提出请求呢?要获得电影,美国的 MPAA = PG-13?

4

1 回答 1

1

由于您的数据已布置好,因此这里没有很好的查询。

如果您可以将您的movies收藏更改为以下内容,那么您的查询将起作用:

   "movieMpaa": {
     "verdict": "Rated PG-13",
     "countries": [
         {
           "mpaa": "IIA",
           "country": ObjectId("4fd79ec34c9fda9d0500007f") 
       },
         {
           "mpaa": "PG-13",
           "country": ObjectId("4fd79ec34c9fda9d05000080") 
        } 
     ]

WhenmovieMpaa.countries是一个对象数组,那么您可以在该数组中查询movieMpaa.countries.country. MongoDB 将识别数组并“钻取”对象。

However, there is another way structure this that probably much easier longer term:

   "movieMpaa": {
     "verdict": "Rated PG-13",
     "countries": {
         ObjectId("4fd79ec34c9fda9d0500007f") : { "mpaa": "IIA" },
         ObjectId("4fd79ec34c9fda9d05000080") : { "mpaa": "PG-13" }
     }

If a country can only have one rating, then technically that countries value is a dictionary of Countries => ratings. The structure above stores them this way.

However, the use of ObjectId is a little ugly there. Note that you can override the ID in the country collection. Consider using the 2 or 3-character ISO codes instead. These are easier to read.

   "movieMpaa": {
     "verdict": "Rated PG-13",
     "countries": {
         "UK" : { "mpaa": "IIA" },
         "US" : { "mpaa": "PG-13" }
     }

db.movies.find({'movieMpaa.countries.US': 'PG-13'})
于 2012-06-13T01:01:28.813 回答