簡體   English   中英

MongoDB-查詢兩個集合

[英]MongoDB - query with two collections

我試圖掌握MongoDB,並且已經在單個集合上進行了一些基本查詢的實驗,但是我想通過某種方式將它們鏈接到查詢中來使用兩個集合。 我有以下帶有電影信息的文件,

電影:

{
      id:  1, 
      title: "abc", 
      release_data: "xxxx",
      IMDBURL: "qwe", 
      genre: ["xx","yy's","zz"]
}

以及另一收藏集中的以下類型的文檔,其中包含有關用戶的信息以及包含他已評分電影的嵌入文檔以及評分本身的信息。

使用者:

{
      id:  1, 
      age: xx, 
      gender: "Y", 
      occupation: "abc", 
      zip_code: "asd", 
      movies:[
      { movie: 1, rating: 5 } , 
      { movie: 2, rating: 3 }, 
      { movie: 3, rating: 4 }, 
      { movie: 4, rating: 3 }
      ]
}

我如何進行查詢以返回至少一次被評為5的電影的標題? 謝謝。

MongoDB:無聯接,無事務

有趣的是,我再也不需要它們了。 與您的示例一樣,您基本上必須問自己需要回答什么,並相應地對數據建模

  • 哪些電影被評為至少五次?
  • 這些電影的名字是什么?

在給定數據模型的情況下,您甚至無法擺脫普通的查詢:您需要一個匯總。 使用以下數據集:

{ "_id" : ObjectId("56c8e58ee99e5c4e87ec3a4e"), "age" : 22, "gender" : "Y", "occupation" : "abc", "zip_code" : "asd", "movies" : [ { "movie" : 1, "rating" : 5 }, { "movie" : 2, "rating" : 3 }, { "movie" : 3, "rating" : 4 }, { "movie" : 4, "rating" : 3 } ] }
{ "_id" : ObjectId("56c8e598e99e5c4e87ec3a4f"), "age" : 22, "gender" : "Y", "occupation" : "abc", "zip_code" : "asd", "movies" : [ { "movie" : 1, "rating" : 5 }, { "movie" : 2, "rating" : 3 }, { "movie" : 3, "rating" : 4 } ] }
{ "_id" : ObjectId("56c8e599e99e5c4e87ec3a50"), "age" : 22, "gender" : "Y", "occupation" : "abc", "zip_code" : "asd", "movies" : [ { "movie" : 1, "rating" : 5 }, { "movie" : 2, "rating" : 3 }, { "movie" : 3, "rating" : 4 } ] }
{ "_id" : ObjectId("56c8e59ae99e5c4e87ec3a51"), "age" : 22, "gender" : "Y", "occupation" : "abc", "zip_code" : "asd", "movies" : [ { "movie" : 1, "rating" : 5 }, { "movie" : 2, "rating" : 3 }, { "movie" : 3, "rating" : 4 } ] }
{ "_id" : ObjectId("56c8e59be99e5c4e87ec3a52"), "age" : 22, "gender" : "Y", "occupation" : "abc", "zip_code" : "asd", "movies" : [ { "movie" : 1, "rating" : 5 }, { "movie" : 2, "rating" : 3 }, { "movie" : 3, "rating" : 4 } ] }

您可以通過以下匯總找到符合條件的電影

db.movies.aggregate([
  { $unwind:"$movies"},
  { $group:{ _id:"$movies.movie", ratings:{ $sum:1 }}},
  { $match:{ ratings:{ $gte:5}}},
  { $project:{ _id:1 }}
])

哪個將返回如下所示的文檔

{ "_id" : 3 }
{ "_id" : 2 }
{ "_id" : 1 }

與上面的樣本數據匹配。 現在,借助這些內容,您可以在相應的集合中查找電影名稱。

聚合,解剖

db.movies.aggregate([

])

要查看各個階段的功能,只需刪除其后的階段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM