Skip to content

Instantly share code, notes, and snippets.

@bootandy
Last active October 1, 2015 05:58
Show Gist options
  • Save bootandy/1933371 to your computer and use it in GitHub Desktop.
Save bootandy/1933371 to your computer and use it in GitHub Desktop.
monogo notes
cheat sheet:
http://cheat.errtheblog.com/s/mongo
for more on update see:
http://www.mongodb.org/display/DOCS/Updating#Updating-update%28%29
======================== DEV ==============================
---search by date:
db.houses.find({"dateadded": { "$gt" : ISODate("2013-01-01")} } )
-- Get by subdocument key field:
db.user_details.find({'field.my_key': {'$exists':true}})
---Bulk update of date field.
db.houses.update( { } , {$set:{'dateadded':new ISODate("2012-02-21")} }, false, true )
-----Distinct values of field: dateadded
db.houses.distinct( 'dateadded')
----- Cheeky way to pull out single field from 1 document:
db.my_table.find({price:60}).my_field
----- For each entry in 'arr' table - take the CSV string - split it into an array:
db.arr.find({}).forEach(function(doc) {
doc['hobbies'] = doc['hobbies'].split(/\s*,\s*/)
db.arr.save(doc)
});
----- Aggregate Example:
-Find top 5 states sorted by zip code]:
db.zips.aggregate([ {$group : {_id:"$state", total:{$sum:1}}}, {$sort:{total:-1}}, {$limit:5} ])
-Group by COL1 and COL2. Then count rows by grouped COL1 + COL2
db.problem11.aggregate( { $project : {'_id':{ n2:'$COL1', m:'$COL2'} } }, { $group: { _id :'$_id', n:{$sum:1} } } )
- Calculating a simple Average
db.perceptions.aggregate( { $match: {an_id:"2"}}, {$group: {_id:"$an_id", avgx: { $avg: "$value"} } } )
- Match all messages that have exactly 2 comments (comments is a nested sub collection inside messages)
db.messages.aggregate( {$unwind:"$comments"}, { $group: {_id:"$_id", sum:{$sum:1}} }, {$match: {sum:2}} )
- Count all of a nested sub collection named comments:
db.messages.aggregate( {$unwind:'$comments'}, { $group: {_id:"result", count:{$sum:1}} } )
----- Sub documents Example:
db.messages.update({'_id': msg_id, 'comments._id': comment_id}, {'$set': {'comments.$.comment': comment_text}
db.messages.update({'_id':msg_id}, {$pull:{'comments':{'_id': 2}}})
====================== Map Reduce ================
# Define Map:
> m
function () {
this.tags.forEach(function (z) {emit(z, {count:1});});
}
# Define Reduce:
> r
function (k, v) {
var total = 0;
for (var i = 0; i < v.length; i++) {
total += v[i].count;
}
return {count:total};
}
# Run it:
>res = db.things.mapReduce(m, r, {out:{inline:1}} )
# To debug:
emit = function emit(k,v ) { print("emit"); print("k:"+k+ "v: "+tojson(v)); }
m.apply(db.things.findOne())
======================= ADMIN ===============================
---- Take a backup of the current table
b = db.my_table_bak; db.my_table.find().forEach( function(o) { b.insert(o) } )
---- View queries:
# Record queries: 2=all, 1=slow, 0=none. see: http://docs.mongodb.org/manual/reference/method/db.setProfilingLevel/
db.setProfilingLevel(2);
# find which collections queries are running against:
db.runCommand ( { distinct: 'system.profile', key: 'ns' } )
db.system.profile.find({"ns" : "mydb.mycollection"}).count()
# How many queries are run against myfield?
db.system.profile.find({"ns" : "mydb.mycollection", "query.my_field": {$exists:true}} ).count()
# Make system.profile bigger (default = 1MB):
db.system.profile.drop()
db.createCollection("system.profile", {capped:true, size:10000000})
db.system.profile.stats() # < To see new size
# Print all ops running for more than 10s:
db.currentOp().inprog.forEach(
function(op) {
if (op.secs_running > 10) {
print ("slow op: "+op.secs_running+ " opid: "+op.opid);
}
}
)
================ Admin Replica Sets ================
# Launch a mongoD
./mongod --shardsvr --dbpath /data/cluster/
# Launch config server: (use 3 in PROD):
./mongod --configsvr --dbpath /data/configdb
# Launch a mongoS (run a mongoS on each client box or each mongoD box)
/mongos --configdb localhost:27019
# To add shards to the cluster:
sh.addShard('localhost:27018')
sh.enableSharding('db')
sh.shardCollection("collection_name", {_id:1}, true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment