0
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

1 Answer 1

1

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}
    ]
)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I forgot to sort. I have just added this part.
But i need to match all the users' Friends in the userrating and sum their weight. Not just match one by one.
Then in 1) you don't filter by your_user_id. And your array as output of 1) should contain all user 's friends ids, and this is what you use as input for 2).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.