Siraj ul Haq
Siraj ul Haq

Reputation: 885

MongoDB: Count number of occurrence of document in collection

I need to count referenced documents in other collection, like I have following scenario:

Books:

{
  id: "123",
  name: "Alpha"
}, {
  id: "124",
  name: "Beta"
}, {
  id: "125",
  name: "Gamma"
}

Users:

{
  id: "234",
  name: "user 1"
  fav_books: ["123", "124"]
}, {
  id: "235",
  name: "user 1"
  fav_books: ["123", "124", "125"]
}, {
  id: "236",
  name: "user 1"
  fav_books: ["123", "125"]
}, 

I need to count each book count in all users collection, Like above scenario should output:

{
  "123": "3",
  "124": "2",
  "125": "2"
}

Upvotes: 0

Views: 247

Answers (1)

user9251303
user9251303

Reputation:

If you're running mongodb 3.4 onwards:

db.Users.aggregate( [ 
          { $unwind: "$fav_books" }, 
          { $sortByCount: "$fav_books" }
          ] )

No need to do a join. You have an array of book id's within each Users document... unless you wanted to display the Books name.

Above code outputs:

{
    "_id" : "123",
    "count" : 3
}
{
    "_id" : "125",
    "count" : 2
}
{
    "_id" : "124",
    "count" : 2
}

Upvotes: 3

Related Questions