FlintSable
5/31/2017 - 11:30 PM

MongoDB Commands

MongoDB Commands

mongod - start the mongo server
mongo - in another terminal open the cli, much like mysql cli
// 4 - Sorting Results
// ================================

// The format of a sort follows db.COLLECTION_NAME.find().sort({FIELD:1})

// A value of 1 is for ascending order.
// A value of -1 is for descending order.

// NOTE: Remember to add .pretty() afterwards so the results are readable!
// In the mongo shell, using the animals collection that you created in the last exercise:

// 1. Show them how to sort by id:
// The id contains a timestamp, so sorting by id will sort by when they were entered to the database.
db.animals.find().sort({_id:1})
db.animals.find().sort({_id:-1})

// 2. Show them how to sort by an integer - numlegs:
db.animals.find().sort({numlegs:1})
db.animals.find().sort({numlegs:-1})


// 3. Show them how to sort by a string - class:
db.animals.find().sort({class:1})
db.animals.find().sort({class:-1})
/* MongoDB Zoo (18.2.3)
 * =================== */

// Dependencies
var express = require("express");
var mongojs = require("mongojs");

// Initialize Express
var app = express();

// Database configuration
// Save the URL of our database as well as the name of our collection
var databaseUrl = "zoo";
var collections = ["animals"];

// Use mongojs to hook the database to the db variable
var db = mongojs(databaseUrl, collections);

// This makes sure that any errors are logged if mongodb runs into an issue
db.on("error", function(error) {
  console.log("Database Error:", error);
});


// Routes
// 1. At the root path, send a simple hello world message to the browser
app.get("/", function(req, res) {
  res.send("Hello world");
});

// 2. At the "/all" path, display every entry in the animals collection
app.get("/all", function(req, res) {
  // Query: In our database, go to the animals collection, then "find" everything
  db.animals.find({}, function(err, found) {
    // Log any errors if the server encounters one
    if (err) {
      console.log(err);
    }
    // Otherwise, send the result of this query to the browser
    else {
      res.json(found);
    }
  });
});

// 3. At the "/name" path, display every entry in the animals collection, sorted by name
app.get("/name", function(req, res) {
  // Query: In our database, go to the animals collection, then "find" everything,
  // but this time, sort it by name (1 means ascending order)
  db.animals.find().sort({ name: 1 }, function(err, found) {
    // Log any errors if the server encounters one
    if (err) {
      console.log(err);
    }
    // Otherwise, send the result of this query to the browser
    else {
      res.json(found);
    }
  });
});

// 4. At the "/weight" path, display every entry in the animals collection, sorted by weight
app.get("/weight", function(req, res) {
  // Query: In our database, go to the animals collection, then "find" everything,
  // but this time, sort it by weight (-1 means descending order)
  db.animals.find().sort({ weight: -1 }, function(err, found) {
    // Log any errors if the server encounters one
    if (err) {
      console.log(err);
    }
    // Otherwise, send the result of this query to the browser
    else {
      res.json(found);
    }
  });
});

// Set the app to listen on port 3000
app.listen(3000, function() {
  console.log("App running on port 3000!");
});
/* Update, Delete and Drop in MongoDB
 * -/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/- */

/* Show the students the following steps (DO NOT SEND IT TO THEM). 
   Explain what each step is doing */

// Make sure you are in your example db from 18.1.1
db
use lessondb

// Show how to update data 
// using db.[COLLECTION_NAME].update()
db.iWantToGoToThere.update({"country": "Morocco"}, {$set: {"continent":"Antartica"}})
// Note that the above will only update the first entry it matches. 

// To update multiple entries, you need to add {multi:true}
db.iWantToGoToThere.update({"country": "Morocco"}, {$set: {"continent":"Antartica"}}, {multi:true})

// Ask the class what they think will happen when you run this command,
// even though a capital doesn't exist
db.iWantToGoToThere.update({"country": "Morocco"}, {$set: {"capital":"Rabat"}})
// answer: it will create the field

// And show the field can now be updated with the same command
db.iWantToGoToThere.update({"country": "Morocco"}, {$set: {"capital":"RABAT"}})

// Show how to push to an array with $push
db.iWantToGoToThere.update({"country": "Morocco"}, {$push: {"majorcities":"Agadir"}})

// Show how to delete an entry with db.[COLLECTION_NAME].remove()
db.iWantToGoToThere.remove({"country":"Morocco"})

// Show how to empty a collection with db.[COLLECTION_NAME].remove()
db.iWantToGoToThere.remove({})

// Show how to drop a collection with db.[COLLECTION_NAME].drop()
db.iWantToGoToThere.drop()

// Show how to drop a database 
db.dropDatabase()



db.animals.insert({"name": "python"}, {"numlegs": 4}, {"class": "reptile"}, {"whatIWouldReallyCallIt": "monty"})
db.animals.insert({"name": "bird"}, {"numlegs": 4}, {"class": "flyer"}, {"whatIWouldReallyCallIt": "birdy"})
db.animals.insert({"name": "python"}, {"numlegs": 4}, {"class": "reptile"}, {"whatIWouldReallyCallIt": "monty"})
db.animals.insert({"name": "python"}, {"numlegs": 4}, {"class": "reptile"}, {"whatIWouldReallyCallIt": "monty"})


// Insert into a collection named animals:
// One entry for each of your five favorite animals.

// Each entry should have
// 1. A field of numlegs with an integer of the number of legs that animal has.
// 2. A field of class with that animal’s class (mammal, reptile, etc).
// 3. A field of weight with an integer of the weight of the animal in pounds (any reasonable weight, really).
// 4. A field of name, with the animal’s name.
// 5. A field of whatIWouldReallyCallIt with the name of what you would call the animal if you got to name it.

// Example:

// {
//   “name”: “Panda”,
//   “numlegs”: 4,
//   “class”: “mammal”,
//   “weight”: 254,
//   “whatIWouldReallyCallIt”: “Captain Fuzzy Face”
// }
/* Query 1 - Creating dbs, inserting data and finding data
 * -/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/- */

// Start up a new database by switching to it.
// NOTE: The db does not exist until you create a collection.
use lessondb

// Show the current db by running db.
db

// Insert data into the lessondb database with this command.
// NOTE: This will create the collection automatically,
// ALSO, TAKE NOTE: the contents of the insert are basically a JS object, 
// and include an array.
db.iWantToGoToThere.insert({"continent": "Africa", "country":"Morocco", "majorcities": ["Casablanca", "Fez", "Marrakech"]})
db.studentsInMyRow.insert({"name": "Bryan", "rownumber": 3, "os": "win32", "hobbies": ["Casablanca", "Fez", "Marrakech"]})
db.studentsInMyRow.insert({"name": "Marissa", "rownumber": 3, "os": "win32", "hobbies": ["Casablanca", "Fez", "Marrakech"]})
db.studentsInMyRow.insert({"name": "Julia", "rownumber": 3, "os": "win32", "hobbies": ["Casablanca", "Fez", "Marrakech"]})


// As a class, come up with 3-5 more countries and 
// insert them into the db using the same syntax as above.

// Observe where the data was entered in the MongoDB instance (in mongod)

// Find all data in a Collection with db.[COLLECTION_NAME].find()
// NOTE: the MongoDB _id was created automatically. 
// This id is specific for each doc in the collection.
db.iWantToGoToThere.find()

// Adding .pretty() makes the data more readable.
db.iWantToGoToThere.find().pretty()

// Find specific data by matching a field.
db.iWantToGoToThere.find({"continent": "Africa"}) 
db.iWantToGoToThere.find({"country": "Morocco"})

// Try a few queries with the examples we came up with as a class.
// Also, pick something that will find more than one entry 
// so we can see how it will return all matches.

// Find specific data by matching an _id. By id: 
db.iWantToGoToThere.find({_id:[COPY AN OBJECTID FROM THE PREVIOUS FIND RESULTS]});
/* 3-INSERTING ANIMALS 
 * ===================================================== */

// An example of animals you can insert into the zoo db
// =================================================================

use zoo
db.animals.insert({"name":"Panda", "numlegs":4, "class":"mammal", "weight": 254, "whatIWouldReallyCallIt":"Captain Fuzzy Face"})
db.animals.insert({"name":"Dog", "numlegs":4, "class":"mammal", "weight": 60, "whatIWouldReallyCallIt":"Captain Fuzzy Face II"})
db.animals.insert({"name":"Lion", "numlegs":4, "class":"mammal", "weight": 300, "whatIWouldReallyCallIt":"Grumbles"})
db.animals.insert({"name":"Zebra", "numlegs":4, "class":"mammal", "weight": 500, "whatIWouldReallyCallIt":"Stripes"})
db.animals.insert({"name":"Chameleon", "numlegs":4, "class":"Reptile", "weight": 5, "whatIWouldReallyCallIt":"Scales"})