Ironhack Day 17

MongoDB:

0. How to start mongo in the terminal:

a. start_mongo

b. open new tab and type mongo

c. open third tab and node index.js

1. Show me element’s name but not its id:

db.enemies.find({”name”: ”Blinky”}, {name: 1, _id:0})

{ ”name” : ”Blinky” }

2. Show property of an embedded document, notice the use of quotations marks (phone is an embedded document of the employees database, since it has different properties, among them ”ext”):

db.employees.find({”phone.ext”: ”2143”})

3. Updating a document:

db.employees.updateOne(
{ ”name”: ”Martin”},
{ $set: { ”phone.ext”: 1234 }}
)

4. Replacing an object of an array:

var susan = {
”name” : ”Susan”,
”age” : 25,
”phone” : { ”personal” : ”555-223-223”, ”work” : ”555-421-426”, ”ext” : 4240 },
”privileges” : ”user”,
}

db.employees.replaceOne(
{ ”name”: ”Martin”},
susan
)

5a. Deleting one element:

db.employees.deleteOne( { ”_id”: ObjectId(”583ea82c58613b64d5df8405”) })

5b. Deleting several elements:

db.employees.deleteMany({ age : { $gte: 30 }})

5c. Delete all:

db.employees.deleteMany({})

6. Use mongoimport to import documents into a collection:

$ mongoimport –db restaurants –collection restaurants –drop –file ~/downloads/primer-dataset.json

7. The only reason to use the $and operator is to apply more than one condition (that isn’t equality) over the same field:

db.users.find({
$and: [
{”age”: {$gt: 18}},
{”age”: {$lt: 30}}
]
})

OR

db.restaurants.find({
$and: [
{”borough”: ”Brooklyn”},
{”grades.score”: {$gte: 80}}
]
}).pretty()

8. Sorting (note: 1 here is for ascending and -1 for descending order):

db.restaurants.find().sort( { ”borough”: 1, ”address.zipcode”: -1 } )

9a. Counting all the number of documents:

db.restaurants.find().count()

9b. Counting certain documents:

db.restaurants.find({”grades.score”: {$gte: 10}}).pretty().count()

10. Find documents according to their positions in the array (here they are in position two):

db.restaurants.find({”grades.1.grade” : ”A”}).pretty()

9. Example of deleting one document from your Mongo DB:

db.projects.remove( { ”name” : ”bla”})