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

查看:30
本文介绍了使用 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.

我搜索了一种使用 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天全站免登陆