MongoDB Flashcards
What kind of database is mongoDB?
NoSQL
What is NoSQL
Not only stuctured query langauge
Difference between SQL and noSQL?
SQL stores data in a table. An entry is called a row/record. Individual items in a row are called a column
noSQL stores data in a collection (looks like JSON). An entry is called a document. Individual items in a document are called fields
Installing community edition on machine
Download
Rename folder and move to User directory
Create another folder with same name + -data
in terminal run: mongod.exe –dbpath=/Users/DRPC/mongodb-data
How to start database?
In the terminal from the mongodb folder run:
mongod.exe –dbpath=/Users/DRPC/mongodb-data
What is robo3t?
a GUI tool for working with mongodb
What language does the mongo shell use?
javascript
How to check if connection to data base was successful using the mongo shell?
run in console:
db.version()
What do we need to install in order to interact with a mongoDB database from node?
mongoDb driver
npm i mongodb
How to connect to mongoDB using node?
const mongodb = require(‘mongodb’);
const MongoClient = mongodb.MongoClient;
const connectionURL = 'mongodb://127.0.0.1:27017'; const databaseName = 'task-manager';
MongoClient.connect(connectionURL,{useNewUrlParser:true,useUnifiedTopology: true },(error,client)=>{
if(error){
return console.log(‘Unable to connect to database’)
}
const db = client.db(databaseName)
});
What is the structure of a mongoDB database?
MongoDB contains databases
Databases contain collections
Collections contain documents
Documents contain fields
how to insert a document into a collection?
db.collection(‘users’).insertOne({
name:’Andrew’,
age:27
},(error,result)=>{
if(error){
return console.log(‘Unable to insert user’)
}
console.log(result.ops) })
How to create a MongoDb client?
const mongodb = require(‘mongodb’)
const MongoClient = mongodb.MongoClient
MongoClient(url,options,callback)
How to create a database?
const db = client.db(‘database-name’)
How to access or creat a collection within a database?
db.collection(‘collection-name’)
What methods can be used to insert documents into a collection
.insertOne(document,callback)
.insertMany(ArrayOfDocuments,callback)
What are gu id’s
globally unique identifiers. Allows mongo db to scale and handle a lot of traffic, without conflict.
What is an Object id?
It is a globally unique 12 byte identifier for a document.
Each 12 byte id constist out of a 4 byte time stamp, a 5 byte random value, and a 3 byte counter starting with a random number.
Are object id’s strings?
No they are 12 byte binary data
What methods can be used to retrieve documents from a collection?
.find()
.findOne()
When searching a data base for an object with a specific id, what method needs to be called an the id string?
new ObjectID()
What is an important difference between the findOne and the find method?
The findOne method takes a callback that returns the required data.
The find method has no callback and doesn’t return anya actual data, instead it returns a cursor.
in order to get the data from the cursor, one needs to call the toArray() method and pass in a callback function.
What is the advantage of having the find method return a cursor instead of the actual data?
It is much more memory efficient, especially when you don’t need the actual data, like when you only want a count of all the different entries that meet a specific criteria.
How to retrieve multiple documents from a collection?
db.collection(‘users’).find({age:33}).toArray((error,response)=>{
if(error){
return console.log(‘error’)
}
console.log(response) })
How to retrieve a single document from a collection
db.collection(‘users’).findOne({name:’Jo’},(error,user)=>{
if(error){
return console.log(error)
}
console.log(user) })
What does CRUD stand for
Create
Read
Update
Delete
How to write a promise?
const doWork = new Promise((resolve,reject)=>{ const a = 1; if(a === 1){ setTimeout(()=>{ resolve([3,4,5]) },5000) }else{ setTimeout(()=>{ reject("Oops") },5000) }
});
doWork.then((result)=>{ console.log(result) }).catch((error)=>{ console.log(error) });
Name the update opperators
$set : sets the value of a field
$currentDate : sets the value to current date
$inc : INcrements the value of the filed by the specified amount.
$min: Only updates the field if the specified value is less than the existing field value
$max: Only updates the field if the specified value is greater than the exisitng field value
$mul : multiplies the value of the field by the specified amount
$rename : renames a field
$setOnInsert : Sets the value of a field if an update results in an insert of a document.
$unset : removes the specified field from a document
how to update a single value in a document
db.collection('users').updateOne({ _id: new ObjectID('5e901baa1161fe3bf83f7649') },{ $set:{ name:'JoJo' } }).then((result)=>{ console.log(result) }).catch((error)=>{ console.log(error) });
What are the two main methods for updating a document
.updateOne()
.updateMany()
how to update multiple values in a document
db.collection(‘users’).updateMany({
age:33
},{
$set:{
age:100
}
}).then((result)=>{
console.log(result)
}).catch((error)=>{
console.log(error)
});
two main methods for deleting a document
.deleteOne()
.deleteMany()
how to delete a single document?
db.collection(‘users’).deleteOne({
age:100
}).then((result)=>{
console.log(result)
}).catch((error)=>{
console.log(error)
});
What is mongoDB Atlas?
Database as a service (DAAS)
Stores data on cloud
Handles replication: maintain redundant copies of data to increase data availability
What is a cluster?
group of servers that store data
What is a replica set?
A cluster where each server stores the same data. This means that each time a document is inserted, redundent copies are stored on each set. This means that if you lose access to a server in a cluster, you wont lose your data.
How to retrieve a range of values?
gte = greater than and equal to lt = less than
{“birth year”:{“$gte”:1985,”$lt”:1990}
connecting to atlas from the mongo shell?
mongo + connection string
mongo “mongodb+srv://sandbox-xa6rd.mongodb.net/test” –username m001-student
How to load data from the mongo shell?
While server is connected:
load(“filename.js”)
How to see a list of databases in mongo shell?
show dbs
How to switch to a specific database in mongo shell?
use db-name
How to see a list of collection in a database from mongo shell?
show collections
How to get a read out of the data in a collection from mongo shell?
db.databaseName.find().pretty()
How to use mongo compass to connect to atlas?
click on cluster. Then click on the primary server. copy the hostname and fill out the individual fields in compass
What is mongoose?
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node. js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB
Mongoose: Creating a client
mongoose.connect(connectionURL,{useNewUrlParser: true,useCreateIndex:true });
Mongoose: Creating a model
const User = mongoose.model('User', { name:{ type:String }, age:{ type:Number } });
Mongoose: Inserting a document
const user = new User({ name:"Bob", age:100 });
user.save().then((result)=>{
console.log(result)
}).catch((error)=>{
console.log(error)
});
Mongoose: How to create a collection
A model is automatically created when a new model is defined. It takes the model name, pluralizes it and sets that as the collection name
Mongoose: difference between data validation and sanitation?
validation: Specifies rules for valid data
sanitation: cleans up data, by removing unwanted characters etc
Mongoose: How to make a field required?
required: true
Mongoose: how to validate input?
validate(value){ if(value < 21){ throw new Error("Not old enough") } }
Which npm package can we use for validation?
npm validator
Mongoose: String sanitation
lowercase: boolean, whether to always call .toLowerCase() on the value
uppercase: boolean, whether to always call .toUpperCase() on the value
trim: boolean, whether to always call .trim() on the value
match: RegExp, creates a validator that checks if the value matches the given regular expression
enum: Array, creates a validator that checks if the value is in the given array.
minlength: Number, creates a validator that checks if the value length is not less than the given number
maxlength: Number, creates a validator that checks if the value length is not greater than the given number
Mongoose: number sanitation
min: Number, creates a validator that checks if the value is greater than or equal to the given minimum.
max: Number, creates a validator that checks if the value is less than or equal to the given maximum.
enum: Array, creates a validator that checks if the value is strictly equal to one of the values in the given array.
Mongoose: How to set default on models?
default: “SomeDefaultValue”
What should be done before data is entered into a database?
The data should be validated and sanitized.
Mongoose: When defining the model, how can we check wether a value includes a specific expression?
validate(value){ if(value.includes("phrase"){ //do something } }