MongoDB:没有 JOINS,没有事务
很有趣,我从来不需要它们中的任何一个。与您的示例一样,您基本上必须问自己需要回答什么并对数据进行相应建模。
鉴于您的数据模型,您甚至无法摆脱普通查询:您需要一个聚合。使用以下数据集:
{ "_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([
])
要查看单个阶段的作用,只需删除它后面的阶段。