如何有效地执行“与众不同"有多个键? [英] How to efficiently perform "distinct" with multiple keys?
问题描述
比如有一个这样的集合:
For example, there is a collection like this:
{市场:'SH',代码:'000001',日期:'2012-01-01',价格:1000}
{市场:'SZ',代码:'000001',日期:'2012-01-01',价格:1000}
{市场:'SH',代码:'000001',日期:'2012-01-02',价格:1000}
{市场:'SZ',代码:'000001',日期:'2012-01-02',价格:1000}
{市场:'SH',代码:'000002',日期:'2012-01-03',价格:1000}
...
{market: 'SH', code: '000001', date: '2012-01-01', price: 1000}
{market: 'SZ', code: '000001', date: '2012-01-01', price: 1000}
{market: 'SH', code: '000001', date: '2012-01-02', price: 1000}
{market: 'SZ', code: '000001', date: '2012-01-02', price: 1000}
{market: 'SH', code: '000002', date: '2012-01-03',price: 1000}
...
该集合包含数千万个文档.
This collection contains tens of millions documents.
我想用两个键调用不同的:
I want to call distinct with two keys:
collection.distinct('market', 'code');
并得到结果:
[{市场:'SH',代码:'000001'},{市场:'SZ',代码:'000001'},{市场:'SH',代码:'000002'}]
[{market: 'SH', code:'000001'}, {market: 'SZ', code:'000001'}, {market: 'SH', code:'000002'}]
由于本机不同命令只接受一个键,我尝试使用 map-reduce 来实现它.但是 map-reduce 对原生不同来说太慢了.在我的一键 distinct 测试中,map-reduce 花费的时间大约是原生 distinct 的十倍.
有没有一种有效的方法来实现多键不同?
As native distinct command accept only one key, I try to implement it by using map-reduce. But map-reduce is far too slow to native distinct. In my one-key distinct test, map-reduce spend about ten times longer than native distinct.
Is there a efficient way to implement multikey distinct?
推荐答案
如果您愿意等待即将发布的 MongoDB 2.2 版本,您可以使用聚合框架高效地运行此查询:
If you are willing to wait for the upcoming 2.2 release of MongoDB, you can run this query efficiently using the aggregation framework:
collection = db.tb;
result = collection.aggregate(
[
{"$group": { "_id": { market: "$market", code: "$code" } } }
]
);
printjson(result);
在我的测试机器上的百万条记录集合中,这运行了 4 秒,而 map/reduce 版本则花费了 1 多分钟.
On a million-record collection on my test machine, this ran in 4 seconds, while the map/reduce version took over a minute.
这篇关于如何有效地执行“与众不同"有多个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!