Fayaz
Fayaz

Reputation: 2124

Get number of followers for specific page in Mongodb

let's say I have a collection called pages as

{
  _id: "pageid",
  name: "Mongodb"
},
{
  _id: "pageid2",
  name: "Nodejs"
}

and user collection as follows

{
  _id : "userid1",
  following: ["pageid"],
  ...
},
{
  _id : "userid2",
  following: ["pageid", "pageid2"],
  ...
}

how could I make a query to retrieve the pages information along with the number of users follow each page in mongodb, expected result as follows

[
  {
    _id: "pageid",
    name: "MongoDB",
    followers: 2
  },
  {
    _id: "pageid2",
    name: "Nodejs",
    followers: 1
  },
]

Upvotes: 1

Views: 75

Answers (1)

turivishal
turivishal

Reputation: 36134

You can use $lookup and $size to count total followers,

db.pages.aggregate([
  {
    $lookup: {
      from: "user",
      localField: "_id",
      foreignField: "following",
      as: "followers"
    }
  },
  {
    $addFields: {
      followers: { $size: "$followers" }
    }
  }
])

Playground

Upvotes: 1

Related Questions