Skip to content

Instantly share code, notes, and snippets.

@joeltaylor
Last active January 5, 2020 18:16
Show Gist options
  • Save joeltaylor/264fd0ce88056672bcb7 to your computer and use it in GitHub Desktop.
Save joeltaylor/264fd0ce88056672bcb7 to your computer and use it in GitHub Desktop.
The Magical Marvels of MongoDB - Code Companion
//************************************
//
// Level 1 concepts
//
//************************************
// Basic data model (BSON)
{
_id: 1,
name: "Magical Database Dust",
price: 25,
ingredients: ["magic", "a grandmother's sneeze"]
}
// Select which database to use
use potion_shop
//-----------------------------
// Create
// -> db.collection.insert()
//-----------------------------
// Adding a potion to the inventory collection
db.inventory.insert({
_id: 1,
name: "Magical Database Dust",
price: 25,
ingredients: ["magic", "a grandmother's sneeze"]
})
// View inventory
db.inventory.find()
//----------------------------
// Update
// -> db.collection.update()
//----------------------------
// Whoops! We entered the wrong price. We need to update all the prices that are 25
// and make them 25.99 (We could use Regex to update all that don't have .99)
db.inventory.update(
{ price: 25 },
{ $set: { price: 25.99 } },
{ multi: true }
)
// A new law has passed, only wizards who are 18+ can purchase potions that contain dragon tongue.
db.inventory.update(
{ ingredients: {$in: "Dragon tongue" } }, // What's cool is we can add as many query operators as we want.
{ $set: { age_limit: 18 } },
{ multi: true }
)
// Upsert - this is esentially find or create. Use case can be a newsletter announcing new potions.
// GOTCHA! Only do this on keys that have a unique index.
db.inventory.update(
{ email: "funny_reference@somthing_magical.com" },
{ email: "funny_reference@somthing_magical.com",
name: "Harry Potter",
age: 10
},
{ upsert: true }
)
// Removing fields - we no longer need age restrictions on dragon tongue.
db.inventory.update( { ingredients: {$in: "Dragon tongue"} }, { $unset: { age: 1 } } )
//----------------------------
// Remove
// -> db.collection.remove()
//----------------------------
// Whoops! Now Dragon tongue is considered a Schedule 1 narcotic! Better remove it
// before the WBI arrests us.
db.inventory.remove({ingredients:{$in: "Dragon tongue"}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment