Skip to content

Instantly share code, notes, and snippets.

View ceccode's full-sized avatar
🏠
Working from home

Francesco Falanga ceccode

🏠
Working from home
View GitHub Profile
@ceccode
ceccode / avg-example.js
Created October 14, 2014 08:18
Get Avg of array using MongoDB MapReduce
db.avgexample.drop();
db.avgexample.insert({"name":"test1", "value": [1,2,3,4]});
db.avgexample.insert({"name":"test1", "value": [5,6,7,8]});
var map = function() {
var sum = 0;
var count = 0;
for (var i = 0; i < this.value.length; i++) {
var mongoose = require('mongoose'),
// Load User model
User = mongoose.model('User'),
// Create Thing schema
thingSchema = new mongoose.Schema({
_user: {
type: ObjectId,
// Desired unique index:
// db.collection.ensureIndex({ firstField: 1, secondField: 1 }, { unique: true})
db.collection.aggregate([
{ $group: {
_id: { firstField: "$firstField", secondField: "$secondField" },
uniqueIds: { $addToSet: "$_id" },
count: { $sum: 1 }
}},
{ $match: {
# mongodb.conf
# Note: if you run mongodb as a non-root user (recommended) you may
# need to create and set permissions for this directory manually,
# e.g., if the parent directory isn't mutable by the mongodb user.
dbpath=/usr/local/var/mongodb
#where to log
logpath=/usr/local/var/log/mongodb/mongo.log