Skip to content

Instantly share code, notes, and snippets.

@tsusanto
Last active August 29, 2015 13:57
Show Gist options
  • Save tsusanto/9925317 to your computer and use it in GitHub Desktop.
Save tsusanto/9925317 to your computer and use it in GitHub Desktop.
//get free account here: https://mongolab.com/plans/
//free plan includes 0.5GB of storage
//refer to http://docs.mongodb.org/manual/applications/crud/
//To list all collections you currently have
db.getCollectionNames();
//To drop a collection
db.testdemo.drop();
//To create a collection. If it doesn't exist yet, it will create it for you automatically.
db.testdemo.save({fn: "Mickey", ln: "Mouse"});
db.testdemo.save({fn: "White", ln: "Snow"});
//To list all records in a collection
db.testdemo.find();
//mongodb does not give error if you attempt to query a collection that does not exist
db.nosuchcollection.find();
//To list top 5 records, sorted by last name desc. To sort in ascending, just change -1 to 1
db.testdemo.find().sort({ln:-1}).limit(5);
//to add a column to an existing record. If no matching record found, it will do nothing, no error either.
db.testdemo.update({ln: "Mouse"}, { $set: { twitter: "mickeymouse"}});
//to update an existing value in an existing record
db.testdemo.update({ln: "Mouse"}, { $set: { twitter: "@mickeymouse", followers: 100}});
//if you set upsert option = true, it will insert if no matching record is found
db.testdemo.update({ln: "Duck"}, { $set: { fn: "Donald"}}, true);
//to find records matching certain value
db.testdemo.find({ln: "Duck"});
//to remove a record based on ObjectId
db.testdemo.remove({"_id":ObjectId("533b52f0acdbe06c2cae720c")})
//to remove a record that matches the following criteria
db.testdemo.remove({ln: "Duck"});
db.testdemo.find(); //verify that record is gone
//to increment a numeric value by 1
db.testdemo.update({ln: "Mouse"}, {$inc: {followers:1}});
db.testdemo.find({ln: "Mouse"}); //verify it got incremented by 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment