简体   繁体   中英

Aggregation and matching fields with an array in java mongodb

movies:{_id:"12",
      name:"comedy",
      rating:[{
        {user_id:"1",rate:5},
        {user_id:"2", rate:8}, 
        {user_id:"3",rate:4}
             }]
      }

I have an array of users[] in java that contains a set of users_ids. (users={"2","3"}); Also, I have a collection of movies that contains the rating of users to the movie.

I want find all movies that are rated by the users in the array and order them by the sum of these users'rate, recomended top3.

I did some modification in your document like

{_id:"12", name:"comedy", rating:[ {user_id:"1",rate:5}, {user_id:"2", rate:8}, {user_id:"3",rate:4} ] }

Try this

db.movies.aggregate([{$unwind:"$rating"},{$group:{_id:"$_id",rating:{$sum:"$rating.rate"}}},{$sort :{"rating":-1}}])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM