Last active
December 10, 2015 14:49
-
-
Save sureshsaggar/4450305 to your computer and use it in GitHub Desktop.
Analytics - Join two collections in MongoDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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