Rank system using Mongodb

Asked

Viewed 88 times

0

I’m having a hard time using the aggregate of Mongodb.

I need to pick up 5 users who collected more items.

username: 'gg_Max',
items: [
    {
      encrypt: "WccmGN3k6vpbfcdVuWmhTT",
      results: {
        collected: [
          "0082",
          "0012"
        ],
        removed: []
      }
    }
]

in case it would be items.results.collected take the size of the Array?

1 answer

1

db.collection.aggregate([
    { $unwind: "$items" },

    { 
        "$group": { 
            "_id": "$_id", 
            collected:{
               $addToSet: "$items.results.collected"
            },
        }
    },
    { $unwind: "$collected" },

    {
        $project: {
          totalcoletado: {
              $size: "$collected" 
          }
       }
    },

    {$sort: { totalcoletado: -1 } },

    {$limit: 5}
])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.