Mongodb聚合-首先创建项目列表并获取项目与评级详细信息的交集
我以前问过他。问题Mongodb聚合-首先创建项目列表并获取项目与评级详细信息的交集,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我以前问过他。问题 { "_id" : ObjectId("5539d45ee3cd0e48e99c3fa6"), "userId" : 1, "movieId" : 6, "rating" : 2.0000000000000000, "timestamp" : 9.80731e+008 } { "_id" : ObjectId("5539d45ee3cd0e48e99c1fa7"), "userId" : 1,
{
"_id" : ObjectId("5539d45ee3cd0e48e99c3fa6"),
"userId" : 1,
"movieId" : 6,
"rating" : 2.0000000000000000,
"timestamp" : 9.80731e+008
}
{
"_id" : ObjectId("5539d45ee3cd0e48e99c1fa7"),
"userId" : 1,
"movieId" : 22,
"rating" : 3.0000000000000000,
"timestamp" : 9.80731e+008
},
{
"_id" : ObjectId("5539d45ee3cd0e48e99c1fa8"),
"userId" : 1,
"movieId" : 32,
"rating" : 2.0000000000000000,
"timestamp" : 9.80732e+008
},
{
"_id" : ObjectId("5539d45ee3cd0e48e99c1fa9"),
"userId" : 2,
"movieId" : 32,
"rating" : 4.0000000000000000,
"timestamp" : 9.80732e+008
},
{
"_id" : ObjectId("5539d45ee3cd0e48e99c1fa3"),
"userId" : 2,
"movieId" : 6,
"rating" : 5.0000000000000000,
"timestamp" : 9.80731e+008
}
然后需要获得给定两个用户(如userId:1和userId:2)的公共(相交)项,如[6,32]
但是现在我需要用它们中的每一个的评级,比如[{“movieId”:6,“user1_评级”:2,“user2_评级”:4},{“movieId”:32,“user1_评级”:2,“user2_评级”:5}]
我怎么能得到这个?
我试着去做
db.collection.aggregate([
{$match: {"$or":[{"userId":2},{"userId":1}]}},
{$group: {_id: "$movieId", users: {$push: {"userId":"$userId","rating":"$rating"}}}},
{$project: { movieId: "$_id", _id: 0,rating:"$users.rating", allUsersIncluded: { $setIsSubset: [ [1,2], "$users.userId"]}}},
{$match: { allUsersIncluded: true }},
{$group: { _id: null, movies: {$push: {"movie":"$movieId","Rating":"$rating"}}}}
])
但是我得到了[{“电影”:6,0:2,1:4},{“电影”:32,0:2,1:5}]最后我实现了我的目标。答案是
db.collection.aggregate([
{$match: {"$or":[{"userId":2},{"userId":1}]}},
{$group: {_id: "$movieId", users: {$addToSet: {"userId":"$userId","rating":"$rating"}}}},
{$project: { movieId: "$_id", _id: 0,user:"$users", allUsersIncluded: { $setIsSubset: [ [1,2], "$users.userId"]}}},
{$match: { allUsersIncluded: true }},
{$group: { _id: null, movies: {$addToSet: {"movie":"$movieId","user":"$user"}}}}
])