Skip to content

Instantly share code, notes, and snippets.

@sureshsaggar
Last active December 10, 2015 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sureshsaggar/4450305 to your computer and use it in GitHub Desktop.
Save sureshsaggar/4450305 to your computer and use it in GitHub Desktop.
Analytics - Join two collections in MongoDB
/*
* Pending - Covert _id to uid or vice versa
*/
// Collection 01 - users
users_map = function() {
// Simply emit the msisdn and 0 for the file length.
// The file length will come from the other collection.
emit(this._id, { msisdn: this.msisdn, file_length: 0 });
}
// Collection 02 - files.files
files_files_map = function() {
emit(this.uid, { file_length: this.length, msisdn: 0});
}
/*
* Reduce function
*/
r = function(key, values) {
var result = {file_length: 0, msisdn: 0};
values.forEach(function(value) {
// Sum up all the file_length from all for this UID (key)
result.file_length += (value.file_length !== null) ? value.file_length : 0;
// Only set msisdn once
if (result.msisdn === 0 && value.msisdn !== null) {
result.msisdn = value.msisdn;
}
});
return result;
}
/*
* Run mapReduce over both collections
*/
res = db.users.mapReduce(users_map, r, {out: {reduce: 'joined'}})
res = db.files.files.mapReduce(files_files_map, r, {out: {reduce: 'joined'}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment