Skip to content

Instantly share code, notes, and snippets.

@kikofernandez
Last active May 10, 2019 10:23
Show Gist options
  • Save kikofernandez/5548409 to your computer and use it in GitHub Desktop.
Save kikofernandez/5548409 to your computer and use it in GitHub Desktop.
Example of a MongoDB map-reduce with a composite key, sorting the result set in the reduce operation. JavaScript example and its correspondent equivalent in Java
db.books.mapReduce(mapFn, reduceFn, { out: { reduce: 'books_rating'}});
{
_id: {
rating: 4,
author: X
},
value: [
{
title: 'Le petit prince',
author: 'Antoine de Saint-Exupéry',
ISBN: 9780440842149,
description: 'Description'
},
...
]
}
var mapFn = function(){
var value = {
title: this.title,
author: this.author,
ISBN: this.ISBN,
description: this.description
};
emit({rating: this.rating, author: this.author.id}, value);
};
Mongo mongo = new Mongo(hosts);
String mapFn = "function(){ var value = {"+
"title: this.title,"+
"author: this.author,"+
"ISBN: this.ISBN,"+
"description: this.description"+
"};"+
"emit({rating: this.rating, author: this.author.id}, value);"+
"}";
String reduceFn = "function(key, values){"+
"return values.sort(function(a,b){"+
"return a.title - b.title;"+
"});"+
"};";
com.mongodb.MapReduceCommand cmd = new com.mongodb.MapReduceCommand(mongo.getDB("bookdb").getCollection("books"),
mapFn, reduceFn, "books_rating", com.mongodb.MapReduceCommand.OutputType.REDUCE, null);
mongo.getDB("bookdb").getCollection("books").mapReduce(cmd);
var mapFn = function(){
var value = {
title: this.title,
author: this.author,
ISBN: this.ISBN,
description: this.description
};
emit({rating: this.rating, author: this.author.id}, value);
};
var reduceFn = function(key, values){
return values.sort(function(a,b){
return a.title - b.title;
});
};
db.books.mapReduce(mapFn, reduceFn, { out: { reduce: 'books_rating'}});
var reduceFn = function(key, values){
return values.sort(function(a,b){
return a.title - b.title;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment