Skip to content

Instantly share code, notes, and snippets.

@leovolving
Created April 30, 2017 18:24
Show Gist options
  • Select an option

  • Save leovolving/3a61c486bf93a32387ef744a27f9c9f9 to your computer and use it in GitHub Desktop.

Select an option

Save leovolving/3a61c486bf93a32387ef744a27f9c9f9 to your computer and use it in GitHub Desktop.
Server-Side Development 2.1.3 - Mongo Basic Drills
//Find the command that retrieves all restaurants.
> db.restaurants.find();
//Find the command that makes the first 10 restaurants appear when
//db.restaurants is alphabetically sorted by the name property.
> db.restaurants.find().sort({name: 1}).limit(10);
//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.
> db.restaurants.findOne({}, {_id: 1});
{ "_id" : ObjectId("59061db8915d29824d0f78b7") }
> db.restaurants.findOne({_id: ObjectId("59061db8915d29824d0f78b7")});
//Write a command that gets all restaurants from the borough of "Queens".
> db.restaurants.find({borough: "Queens"});
//Write a command that gives the number of documents in db.restaurants.
> db.restaurants.count();
//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 zip code property.
> db.restaurants.find({"address.zipcode": "11206"}).count();
//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.
> db.restaurants.findOne({}, {_id: 1});
{ "_id" : ObjectId("59061db8915d29824d0f78b7") }
> db.restaurants.remove({_id: ObjectId("59061db8915d29824d0f78b7")});
WriteResult({ "nRemoved" : 1 })
> db.restaurants.findOne({_id: ObjectId("59061db8915d29824d0f78b7")});
null
//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.
> db.restaurants.findOne({}, {_id: 1});
{ "_id" : ObjectId("59061db8915d29824d0f78b7") }
> db.restaurants.updateOne({_id: ObjectId("59061db8915d29824d0f78b7")}, {$set: {name: "Bizz Bar Bang"}});
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.restaurants.findOne({_id: ObjectId("59061db8915d29824d0f78b7")}, {name: 1, _id: 1});
{ "_id" : ObjectId("59061db8915d29824d0f78b7"), "name" : "Bizz Bar Bang" }
//Uh oh, two zip codes are being merged! The '10035' zip code is being merged with '10036'.
//Write a command that updates values accordingly.
> db.restaurants.updateMany({"address.zipcode": "10035"}, {$set: {"address.zipcode": "10036"}});
{ "acknowledged" : true, "matchedCount" : 87, "modifiedCount" : 87 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment