Last active
January 5, 2017 16:07
-
-
Save andrewlorenz/ac13b6a9200f2ed85bca071a3fcbff6d to your computer and use it in GitHub Desktop.
mongo cheat sheet - various cope snippets for manipulating databases and collections
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
Increment counter: | |
db.analytics.update({"url" : "www.example.com"},{"$inc" : {"pageviews" : 1}}) | |
Adding/Updating a field in a document: | |
db.blog.posts.update({"author.name" : "joe"}, {"$set" : {"author.name" : "joe schmoe"}}) | |
db.positions.update({},{$set:{pos_short_status:"O"}},{upsert:false,multi:true}); | |
db.clients.update({cli_status:"N"},{$set:{cli_status:"A"}},{upsert:false,multi:true}); | |
Removing a field from a document: | |
db.users.update({"name" : "joe"}, ... {"$unset" : {"favorite book" : 1}}) | |
Renaming a field in a collection: | |
db.usrGrades.update({},{$rename:{"grdUsr":"grd_cap_id"}},{upsert:false,multi:true}); | |
finding docs in a collection that don't match up with another collection: | |
pos = db.positions.find({},{id:1}).map(function(col){return col._id;}); | |
db.positionTests.find({pot_pos_id:{$nin:pos}}); | |
aggregating counts/totals based on a selected field (GROUP BY) | |
-- where alerts collection includes alt_slot ['M','A','E'], and alt_run_cnt [numeric run count] | |
db.alerts.aggregate([{$group:{_id:"$alt_slot",count:{$sum:1},tot_run_cnt:{$sum:"$alt_run_cnt"}}}]) | |
Renaming a collection: | |
db.userMap.renameCollection("userCMap"); | |
Export records from a mongo instance: | |
mongoexport --port [nnnnn] --db pfm --collection users --out /this/users.dat | |
Import records into a mongo instance: | |
mongoimport --port [nnnnn] --host myhost --db pfm --collection users < /this/users.dat | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment