puppeteer701
puppeteer701

Reputation: 1285

Search for most common "data" with mongoose, mongodb

My structure.

User: 
{
  name: "One",
  favoriteWorkouts: [ids of workouts],
  workouts: [ { name: "My workout 1" },...]
}

I want to get list of favorits/hottest workouts from database.

db.users.aggregate(
    { $unwind : "$favorite" },
    { $group : { _id : "$favorite" , number : { $sum : 1 } } },
    { $sort : { number : -1 } }
)

This returns

{
    "hot": [
    {
       "_id": "521f6c27145c5d515f000006",
       "number": 1
    },
    {
       "_id": "521f6c2f145c5d515f000007",
       "number": 1
    },...
]}

But I want

{
   hot: [
   {object of hottest workout 1, object of hottest workout 2,...}
]}

How do you sort hottest data and fill the result with object, not just ids?

Upvotes: 0

Views: 354

Answers (1)

sfritter
sfritter

Reputation: 891

You are correct to want to use MongoDB's aggregation framework. Aggregation will give you the output you are looking for if used correctly. If you are looking for just a list of the _id's of all users' favorite workouts, then I believe that you would need to add an additional $group operation to your pipeline:

db.users.aggregate(
    { $unwind : "$favoriteWorkouts" },
    { $group : { _id : "$favoriteWorkouts", number : { $sum : 1 } } },
    { $sort : { number : -1 } },
    { $group : { _id : "oneDocumentWithWorkoutArray", hot : { $push : "$_id" } } }  
)

This will yield a document of the following form, with the workout ids listed by popularity:

{
    "_id" : "oneDocumentWithWorkoutArray",
    "hot" : [
        "workout6",
        "workout1",
        "workout5",
        "workout4",
        "workout3",
        "workout2"
    ]
}

Upvotes: 1

Related Questions