Skip to content

Instantly share code, notes, and snippets.

@philipp-spiess
Forked from anonymous/example2.js
Created April 10, 2012 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save philipp-spiess/2354750 to your computer and use it in GitHub Desktop.
Save philipp-spiess/2354750 to your computer and use it in GitHub Desktop.
MongoDB CRUD and MapReduce
db.foo.insert( { name: "Mario", fach: ["E", "D"] } );
db.foo.insert( { name: "Philipp", fach: ["PR", "D"] } );
db.foo.find();
db.foo.find( { name: "Mario" } );
db.foo.find( { fach: { $in : [ "E", "M" ] } } );
db.foo.update( { name: "Mario" }, { $push: { fach: "M" } } );
db.foo.find( { name: "Mario" } );
db.foo.ensureIndex( { name : 1 } );
db.foo.remove( { "name" : "Philipp" } );
db.foo.find();
db.things.insert( { _id : 1, tags : ['dog', 'cat'] } );
db.things.insert( { _id : 2, tags : ['cat'] } );
db.things.insert( { _id : 3, tags : ['mouse', 'cat', 'dog'] } );
db.things.insert( { _id : 4, tags : [] } );
db.things.insert( { _id : 5 } );
function map() {
if( typeof this.tags != 'undefined' ) {
this.tags.forEach( function( tag ){
emit( tag , { count : 1 } );
});
}
}
function reduce(key , values) {
var total = 0;
for ( var i=0; i < values.length; i++) {
total += values[i].count;
}
return { count : total };
}
res = db.things.mapReduce(map, reduce, { out : "myoutput" } );
print("Try db.myoutput.find().sort( { \"value.count\" : -1 } );");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment