Skip to content

Instantly share code, notes, and snippets.

@bitgord
Last active December 13, 2016 05:30
Show Gist options
  • Save bitgord/b096c4e74df4d52891666a8ed5f9ce2f to your computer and use it in GitHub Desktop.
Save bitgord/b096c4e74df4d52891666a8ed5f9ce2f to your computer and use it in GitHub Desktop.
Quick Mongo Setup and CRUD Syntax
// Start Mongod // From terminal run mongod
// start mongo shell // from terminal run mongo
// Create a new Collection
db.createCollection('[[name]]')
// Create a User
db.createUser( { "user" : "[[name]]",
"pwd": "[[password]]" } )
// Show collections
show collections
// Delete a collection
db.[[db name]].drop()
// Insert data
db.[[insert db]].insert({ [[insert json]] })
// show databases
show dbs // to see a list of databases
// Use a database
use [[insert db]] // to use a database
// Search a database
db.customers.find()
db.customers.find().pretty() // to make json easier to read
// Clear the console
cls
// Insert multiple things // Note Mongo gives items a unique id automatically
db.[[db]].insert([
{
first_name:"Michael", last_name:"Gord"
},
{
first_name:"MLG", last_name:"Blockchain"
}
])
// Update database // Get object Id from querying database
db.[[db]].update({_id: ObjectId("[[insert id]]")}, {
$set: {
first_name: "x",
age: "25",
}})
// Only set if it meets requirements
db.[[db]].update{first_name: "Michael"}, {
$set: {
first_name: "x",
age: "25",
}}, {upsert: true}) // upsert is a combination of update and insert
// Remove field
db.[[db name]].update({_id: ObjectId("[[insert id]]")}, {$unset: {first_name: 1}}) // or whatever field you want to unset
// Remove greater than
db.[[db name]].renive({age:{$gt:30}}. true) // or whatever var above you want to delete
// Increment age
db.[[db name]].update({_id: ObjectId("[[insert id]]")}, {$inc: {age: 1}}) // inc amount you want to increment
// Insert a boolean + date
db.[[db]].insert({age: 25, birthdate: new Date('Sept 10,1981')})
// Query database to find something
db.[[db]].find({first_name:"Michael"})
// Only return specific item // This example only returns first_name
db.[[db]].find({last_name:"gord"), {first_name:"Michael"})
// Only return one item
db.[[db]].findOne({first_name:"Michael"})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment