使用MongoDB的map reduce选择不同的多个字段 [英] Select distinct more than one field using MongoDB's map reduce

查看:127
本文介绍了使用MongoDB的map reduce选择不同的多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在MongoDB上执行以下SQL语句:

I want to execute this SQL statement on MongoDB:

SELECT DISTINCT book,author from library

到目前为止,MongoDB的DISTINCT一次仅支持一个字段.对于多个字段,我们必须使用GROUP命令或map-reduce.

So far MongoDB's DISTINCT only supports one field at a time. For more than one field, we have to use GROUP command or map-reduce.

我已经用Google搜索了一种使用GROUP命令的方法:

I have googled a way to use GROUP command:

db.library.group({ 
    key: {book:1, author:1}, 
    reduce: function(obj, prev) { if (!obj.hasOwnProperty("key")) { 
        prev.book = obj.book; 
        prev.author = obj.author; 
    }}, 
    initial: { } 
});  

但是,这种方法最多仅支持10,000个键.有人知道如何使用map reduce解决这个问题吗?

However this approach only supports up to 10,000 keys. Anyone know how to use map reduce to solve this problem?

推荐答案

看看此文章解释了如何在MongoDB中使用map-reduce查找独特的文章.

Take a look at this article which explains how to find unique articles using map-reduce in MongoDB.

您的emit语句将类似于:

Your emit statement is going to look something like:

emit({book: this.book, author: this.author}, {exists: 1});

因为您不在乎每个分组有多少,所以您的reduce甚至比示例更简单.

and your reduce can be even simpler than the example since you don't care about how many there are for each grouping.

return {exists: 1};

这篇关于使用MongoDB的map reduce选择不同的多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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