我想在MongoDB上执行这个SQL语句:
SELECT DISTINCT book,author from library
Run Code Online (Sandbox Code Playgroud)
到目前为止,MongoDB的DISTINCT一次只支持一个字段.对于多个字段,我们必须使用GROUP命令或map-reduce.
我用Google搜索了一种使用GROUP命令的方法:
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: { }
});
Run Code Online (Sandbox Code Playgroud)
但是,此方法仅支持10,000个密钥.有谁知道如何使用map reduce来解决这个问题?
看看这篇文章,它解释了如何在 MongoDB 中使用 map-reduce 查找独特的文章。
你的emit 语句看起来像这样:
emit({book: this.book, author: this.author}, {exists: 1});
Run Code Online (Sandbox Code Playgroud)
并且您的 reduce 可能比示例更简单,因为您不关心每个分组有多少。
return {exists: 1};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6873 次 |
| 最近记录: |