node.jsmongodbmongoosesocial-media-like

Getting number of likes for a user in all his posts using mongodb


Hi I want to build a leader board that will rank users based on the likes they have accumulated in all their posts.

My database for Posts

  user: {
    type: Schema.Types.ObjectId,
  },
  text: {
    type: String,
    required: true,
  },
  imageURL: {
    type: [String],
  },
  name: {
    type: String,
    required: true,
  },
  category: {
    type: String,
  },
  likes: [
    {
      user: {
        type: Schema.Types.ObjectId,
      },
    },
  ],
  date: {
    type: Date,
    default: Date.now,
  }

My database for user:


  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  },
  date: {
    type: Date,
    default: Date.now,
  },

I have tried various queries and aggregation functions but I am not able to get the right solution for that. Is there another way to do get the list. I want to get a list of users and total likes they got in all their posts combined. How can I do that ?


Solution

  • You can try this query

    db.collection.aggregate([
      {
        $project: {
          user: 1,
          numberOfLikes: {
            $cond: {
              if: {
                $isArray: "$likes"
              },
              then: {
                $size: "$likes"
              },
              else: "NA"
            }
          }
        }
      }
    ])
    

    You can find demo of this query here