I have a database in MongoDb that contains two collections: 'categories' and 'articles'. I'm using Mongoose on NodeJs to connect to the database and read the categories. I want to calculate the number of articles for a category without making an additional request/query, so it would be perfect if I could solve this at the database level.
An item from the 'categories' collection looks like:
{
'_id' : ObjectId("..."),
'feed_id' : 1,
'name': 'Blog posts'
}
An item from the 'articles' collection looks like:
{
'_id' : ObjectId("..."),
'feed_id' : 1,
'title': 'Article title',
'published' : '12/09/2012',
...
}
so the categories and articles are linked using the 'feed_id' field.
I would like to export all categories together with a corresponding number of articles:
{
'_id' : ObjectId("..."),
'feed_id' : 1,
'name': 'Blog posts',
'no_articles': 4
}
I'm not sure how exactly I should do this:
1) Create a 'no_articles' field in the categories collection? If yes, I would like this to be updated automatically when a document is inserted or deleted from the articles collection.
2) Sum up the articles into 'no_articles' when categories are read?
I read something about MapReduce and group, but didn't quite understand if it's possible to use them for this particular task.