Mongodb 聚合 - 首先创建项目列表并获取项目与评级详细信息的交集

Mongodb aggregation - first create item list and get intersect of items with rating details

我之前问过。问题

    {
    "_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_rating" : 2,"user2_rating" : 4} ,{"movieId":32,"user1_rating" : 2,"user2_rating" : 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"}}}}
])

但我得到 [ {"movie":6,0 : 2,1 : 4},{"movie":32,0 : 2,1 : 5} ]

最后我得到了我的 target.The 答案是

    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"}}}}
])