Mongodb聚合 - 首先创建项目列表并获得具有评级详细信息的项目的交叉

时间:2015-07-06 13:17:32

标签: mongodb aggregation-framework

之前我问过question 。问题

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

但我得到[{&#34;电影&#34;:6,0:2,1:4},{&#34;电影&#34;:32,0:2,1:5}] < / p>

1 个答案:

答案 0 :(得分:0)

最后我实现了我的目标。答案是

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