Skip to content

Instantly share code, notes, and snippets.

@hjanuschka
Last active October 12, 2015 14:17
Show Gist options
  • Save hjanuschka/6fe70ca46c8b681a48d8 to your computer and use it in GitHub Desktop.
Save hjanuschka/6fe70ca46c8b681a48d8 to your computer and use it in GitHub Desktop.
db.uploads.aggregate([
{
$group: { _id: { userId: '$userId' }, formFields: { $addToSet: '$formFields'} }
},
{
$unwind:"$formFields"
},
{
$group: { _id: "$_id", formFieldsCount: { $sum:1} }
}
]);
db.uploads.mapReduce(
function () {
emit( this.userId, this.formFields );
},
function (key,values) {
var reduced = {
};
values.forEach(function(value) {
for ( var k in value ) {
if ( !reduced.hasOwnProperty(k) )
reduced[k] = [];
if ( reduced[k].indexOf( value[k] ) == -1 )
reduced[k].push(values[k]);
}
});
return reduced;
},
{
"finalize": function(key,value) {
for (var k in value) {
if ( Object.prototype.toString.call( value[k] ) !== '[object Array]') {
var replace = [];
replace.push( value[k] );
value[k] = replace;
}
}
return value;
},
"out": { "inline": 1 }
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment