[英]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([
{ $unwind:"$movies"},
,:数组的内容也不能以对我们有用的方式直接检查,因此我们需要解构数组。 对于每个数组项目,基本上都会复制父文档。 { $group:{ _id:"$movies.movie", ratings:{ $sum:1 }}},
:每次找到特定电影时{ $group:{ _id:"$movies.movie", ratings:{ $sum:1 }}},
我们都会增加计数器的ratings
。 因此,每次找到特定电影的电影等级时,计数器都会增加。 { $match:{ ratings:{ $gte:5}}},
我们只希望被评估至少5次的文档 { $project:{ _id:1 }}
:最后但并非最不重要的一点,因为我们只想要电影的ID,所以我们删除了其他所有内容。 ])
要查看各个阶段的功能,只需删除其后的阶段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.