Reputation: 17
movies: {
_id: "1"
name: "comedy"
userratings: [{
user_id: "11",
count: 4
}, {
user_id: "22",
count: 2
}]
}
movies: {
_id: "2"
name: "funny"
userratings: [{
user_id: "22",
count: 8
}]
}
users: {
_id: "11",
name: "jhon",
userFriends: [{
user_id: "22"
}, {
user_id: "12"
}]
}
users: {
_id: "22",
name: "tom",
userFriends: [{
user_id: "11"
}]
}
I have two collections: users and movies. The users collection consists of users info and his friends list. The movies collection consists of movies info and the rating of users to the movie.
My question is: how I can find the movies that are rated by a user's friends but not the user,and order them by the sum of friends'ratings count, limit 5 records.
I am using java with mongodb
Upvotes: 0
Views: 153
Reputation: 2308
You need to implement this operation at your application level, i.e. using Java code. MongoDB is a document store, so it doesn't support relations between collections and what you want to do involves a relation like movies -> user_id -> users -> friends. You need to retrieve separately users and movies using Java and implement the join in your Java code. You won't be able to do this with one single MongoDB query.
Assuming that a user cannot be friends with him/herself, I would do it like this:
1) Get all userFriends from users with _id = (your_user_id):
users.find({_id : (your_user_id)}, {userFriends.user_id : 1})
2) Get all documents from movies having one userratings.user_id = (one of the userFriends from step 1). + group by userratings.count + limit 5. Something like this:
movies.aggregate(
[
{$match : {userratings : {user_id : { $in (userFriends)}}},
{$group : {_id : _id, count : {$sum : userratings.count}}},
{$sort : {count : 1}},
{$limit : 5}
]
)
Upvotes: 1