Skip to content

Instantly share code, notes, and snippets.

@goldtreefrog
Created February 6, 2018 18:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goldtreefrog/84e4a7247840eb16288d0463b66c5f08 to your computer and use it in GitHub Desktop.
Save goldtreefrog/84e4a7247840eb16288d0463b66c5f08 to your computer and use it in GitHub Desktop.
Get all: Retrieve all restaurants.
db.restaurants.find()
Limit and sort: Make the first 10 restaurants appear when db.restaurants is alphabetically sorted by the name property.
db.restaurants.find({},{name: 1}).sort({name: 1}).limit(10);
Get by _id - Retrieve a single restaurant by _id. (First get the _id for one of the restaurants.)
const myId = db.restaurants.findOne()._id;
db.restaurants.findOne({_id: myId});
Get by value: All restaurants from the borough of "Queens".
db.restaurants.find({borough: "Queens"}, {name: 1, "address.zipcode": 1});
Count: Give the number of documents in db.restaurants.
db.restaurants.find().count();
Count by nested value: 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();
Delete by id: Delete a document found by id. (First get the _id for one of the restaurants.)
const delId = db.restaurants.findOne()._id;
db.restaurants.remove({_id: delId});
Update a single document: Set the name property of a document with a specific _id to 'Bizz Bar Bang'. (Keep all other fields.)
const upId = db.restaurants.findOne()._id;
db.restaurants.updateOne({_id: upId}, {$set: {name: "Bizz Bar Bang"}});
db.restaurants.findOne({_id: upId}); // see our changes
Update many documents: Change all zip codes that equal 10035 to 10036 (because someone, presumably with authority at the Post Office, decided to merge them)
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