繁体   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