Skip to content

Instantly share code, notes, and snippets.

@RobertVFrazier
Created May 14, 2018 15:03
Show Gist options
  • Save RobertVFrazier/81639f013b31b1ccfbb1428770b0f081 to your computer and use it in GitHub Desktop.
Save RobertVFrazier/81639f013b31b1ccfbb1428770b0f081 to your computer and use it in GitHub Desktop.
Mongo basics drills
1) Get all
Find the command that retrieves all restaurants.
db.restaurants.find()
2) Limit and sort
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);
3) 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.
var objectId = db.restaurants.findOne({}, {_id: 1})._id;
db.restaurants.findOne({_id: objectId});
4) Get by value
Write a command that gets all restaurants from the borough of "Queens".
db.restaurants.find({borough: "Queens"});
5) Count
Write a command that gives the number of documents in db.restaurants.
db.restaurants.count();
3950
6) 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 zip code property.
db.restaurants.count({"address.zipcode": "11206"});
15
7) 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.
var objectId = db.restaurants.findOne({}, {_id: 1})._id;
db.restaurants.remove({_id: objectId});
(This command will verify it's gone.)
db.restaurants.find({_id: objectId}).count();
8) 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.
var objectId = db.restaurants.findOne({}, {_id: 1})._id;
db.restaurants.updateOne({_id: objectId}, {$set: {name: "Bizz Bar Bang"}});
(This command will verify it's changed.)
db.restaurants.find({_id: objectId});
9) Update many documents
Uh oh, two zip codes are being merged! The '10035' zip code is being retired, and addresses with '10035' will now fall under the '10036' zip code. Write a command that updates values accordingly.
db.restaurants.count({"address.zipcode": "10035"});
12
db.restaurants.updateMany({"address.zipcode": "10035"}, {$set: {"address.zipcode": "10036"}});
(These commands will verify they're changed.)
db.restaurants.find({"address.zipcode": "10035"}).count();
db.restaurants.find({"address.zipcode": "10036"}).count();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment