MongoDB - 读取单个查询中的类别和文章数 [英] MongoDB - Reading categories and number of articles in a single query

查看:269
本文介绍了MongoDB - 读取单个查询中的类别和文章数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MongoDb中有一个数据库,包含两个集合:'categories'和'articles'。
我在NodeJ上使用Mongoose连接到数据库并读取类别。我想计算一个类别的文章数量,而不进行额外的请求/查询,所以如果我可以在数据库级别解决这个问题,这将是完美的。

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'
}

$ b b

articles集合中的项目如下所示:

An item from the 'articles' collection looks like:

{
'_id' : ObjectId("..."),
'feed_id' : 1,
'title': 'Article title',
'published' : '12/09/2012',
...
}

'feed_id'字段。

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
}

我应该这样做:

1)在类别集合中创建no_articles字段?如果是,

2)在阅读类别时将文章归纳为no_articles?

我读了一些关于MapReduce和group的内容,但是不太明白是否可以使用它们来完成这个任务。

I read something about MapReduce and group, but didn't quite understand if it's possible to use them for this particular task.

感谢大家的帮助。

推荐答案

这是传统关系数据库真正闪耀的用例之一。

This is one of use cases where traditional relational databases really shine.

在mongodb中使用一个查询是不可能的。你提到的 no_articles 字段是要走的路。这种方法的公共名(无论如何是Rails人)是: 计数器缓存列 。我对Mongoose不是很熟悉,所以我不知道它会不会为你保留那个字段。 MongoDB本身肯定不会做。但是维护它本身不是很多工作,你只需要准确。

It is impossible to do that with one query in mongodb. The "no_articles field" you mentioned is the way to go. Common name (among Rails people, anyway) for this approach is: Counter Cache Column. I am not very familiar with Mongoose, so I don't know whether it will maintain that field for you or not. MongoDB itself certainly won't do it. But maintaining it yourself isn't a lot of work, you just need to be accurate.

我建议你在读类别时不要计数文章。这是 N + 1查询 问题和计数器缓存列是为了防止它。

I advise against counting articles when you read categories. This is a classic example of N+1 query problem and counter cache column is there to prevent it.

这篇关于MongoDB - 读取单个查询中的类别和文章数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆