Skip to content

Instantly share code, notes, and snippets.

@mikeymaio
Created December 23, 2016 16:40
Show Gist options
  • Save mikeymaio/9299ca61942228113d65f90ba52058b9 to your computer and use it in GitHub Desktop.
Save mikeymaio/9299ca61942228113d65f90ba52058b9 to your computer and use it in GitHub Desktop.
MongoDb Basics Drills
// Get all
// Find the command that retrieves all restaurants.
// ANSWER:
db.restaurants.find()
// Limit and sort
// Find the command that the first 10 restaurants that appear when db.restaurants is alphabetically sorted by the name property.
// ANSWER:
db.restaurants.find().sort({name: 1}).limit(10)
// Get by _id
// Retrieve a single restaurant by _id from the restaurants collection. This means you'll first need to get the _id for one of the restaurants imported into the database.
// ANSWER:
db.restaurants.findOne();
copy ObjectId
db.restaurants.find({_id : ObjectId("585d45a7c49f5290fda85b04")});
// Get by value
// Write a command that gets all restaurants from the borough of "Queens”.
// ANSWER:
db.restaurants.find({borough: "Queens"});
// Count
// Write a command that gives the number of documents in db.restaurants
// ANSWER:
db.restaurants.count()
// Count by nested value
// Write a command that gives the number of restaurants whose zip code value is '11206'. Note that this property is at document.address.zipcode, so you'll need to use dot notation to query on the nested zipcode property.
// ANSWER:
db.restaurants.find({'address.zipcode': "11206"}).count()
// Delete by id
// Write a command that deletes a document from db.restaurants. This means you'll first need to get the _id for one of the restaurants imported into the database.
// ANSWER:
db.restaurants.findOne();
copy ObjectId
db.restaurants.remove({_id : ObjectId("585d45a5c49f5290fda7f9d7”)});
// Update a single document
// Write a command that sets the name property of a document with a specific _id to 'Bizz Bar Bang'. Make sure that you're not replacing the existing document, but instead updating only the name property.
// ANSWER:
db.restaurants.findOne();
copy ObjectId
db.restaurants.update({_id : ObjectId("585d45a5c49f5290fda7f9d7")}, {$set: {name: "BizzBarBang"}})
// Update many documents
// Uh oh, two zip codes are being merged! The '10035' zipcode is being merged with '10036'. Write a command that updates values accordingly.
// ANSWER:
db.restaurants.updateMany( {'address.zipcode': '10035'}, {$set: {'address.zipcode': '10036'}});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment