MongoDB Flashcards

1
Q

What kind of database is mongoDB?

A

NoSQL

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is NoSQL

A

Not only stuctured query langauge

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Difference between SQL and noSQL?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Installing community edition on machine

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to start database?

A

In the terminal from the mongodb folder run:

mongod.exe –dbpath=/Users/DRPC/mongodb-data

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is robo3t?

A

a GUI tool for working with mongodb

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What language does the mongo shell use?

A

javascript

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to check if connection to data base was successful using the mongo shell?

A

run in console:

db.version()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What do we need to install in order to interact with a mongoDB database from node?

A

mongoDb driver

npm i mongodb

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How to connect to mongoDB using node?

A

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)

});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the structure of a mongoDB database?

A

MongoDB contains databases

Databases contain collections

Collections contain documents

Documents contain fields

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

how to insert a document into a collection?

A

db.collection(‘users’).insertOne({
name:’Andrew’,
age:27
},(error,result)=>{
if(error){
return console.log(‘Unable to insert user’)
}

    console.log(result.ops)
})
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How to create a MongoDb client?

A

const mongodb = require(‘mongodb’)

const MongoClient = mongodb.MongoClient

MongoClient(url,options,callback)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How to create a database?

A

const db = client.db(‘database-name’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How to access or creat a collection within a database?

A

db.collection(‘collection-name’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What methods can be used to insert documents into a collection

A

.insertOne(document,callback)

.insertMany(ArrayOfDocuments,callback)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What are gu id’s

A

globally unique identifiers. Allows mongo db to scale and handle a lot of traffic, without conflict.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is an Object id?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Are object id’s strings?

A

No they are 12 byte binary data

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What methods can be used to retrieve documents from a collection?

A

.find()

.findOne()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

When searching a data base for an object with a specific id, what method needs to be called an the id string?

A

new ObjectID()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is an important difference between the findOne and the find method?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the advantage of having the find method return a cursor instead of the actual data?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How to retrieve multiple documents from a collection?

A

db.collection(‘users’).find({age:33}).toArray((error,response)=>{
if(error){
return console.log(‘error’)
}

    console.log(response)
})
25
Q

How to retrieve a single document from a collection

A

db.collection(‘users’).findOne({name:’Jo’},(error,user)=>{
if(error){
return console.log(error)
}

    console.log(user)
})
26
Q

What does CRUD stand for

A

Create
Read
Update
Delete

27
Q

How to write a promise?

A
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)
});
28
Q

Name the update opperators

A

$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

29
Q

how to update a single value in a document

A
db.collection('users').updateOne({
        _id: new ObjectID('5e901baa1161fe3bf83f7649')
    },{
        $set:{
            name:'JoJo'
        }
    }).then((result)=>{
        console.log(result)
    }).catch((error)=>{
        console.log(error)
    });
30
Q

What are the two main methods for updating a document

A

.updateOne()

.updateMany()

31
Q

how to update multiple values in a document

A

db.collection(‘users’).updateMany({
age:33
},{
$set:{
age:100
}
}).then((result)=>{
console.log(result)
}).catch((error)=>{
console.log(error)
});

32
Q

two main methods for deleting a document

A

.deleteOne()

.deleteMany()

33
Q

how to delete a single document?

A

db.collection(‘users’).deleteOne({
age:100
}).then((result)=>{
console.log(result)
}).catch((error)=>{
console.log(error)
});

34
Q

What is mongoDB Atlas?

A

Database as a service (DAAS)

Stores data on cloud

Handles replication: maintain redundant copies of data to increase data availability

35
Q

What is a cluster?

A

group of servers that store data

36
Q

What is a replica set?

A

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.

37
Q

How to retrieve a range of values?

A
gte = greater than and equal to
lt = less than

{“birth year”:{“$gte”:1985,”$lt”:1990}

38
Q

connecting to atlas from the mongo shell?

A

mongo + connection string

mongo “mongodb+srv://sandbox-xa6rd.mongodb.net/test” –username m001-student

39
Q

How to load data from the mongo shell?

A

While server is connected:

load(“filename.js”)

40
Q

How to see a list of databases in mongo shell?

A

show dbs

41
Q

How to switch to a specific database in mongo shell?

A

use db-name

42
Q

How to see a list of collection in a database from mongo shell?

A

show collections

43
Q

How to get a read out of the data in a collection from mongo shell?

A

db.databaseName.find().pretty()

44
Q

How to use mongo compass to connect to atlas?

A

click on cluster. Then click on the primary server. copy the hostname and fill out the individual fields in compass

45
Q

What is mongoose?

A

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

46
Q

Mongoose: Creating a client

A

mongoose.connect(connectionURL,{useNewUrlParser: true,useCreateIndex:true });

47
Q

Mongoose: Creating a model

A
const User = mongoose.model('User', {
    name:{
        type:String
    },
    age:{
        type:Number
    }
});
48
Q

Mongoose: Inserting a document

A
const user = new User({
    name:"Bob",
    age:100
});

user.save().then((result)=>{
console.log(result)
}).catch((error)=>{
console.log(error)
});

49
Q

Mongoose: How to create a collection

A

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

50
Q

Mongoose: difference between data validation and sanitation?

A

validation: Specifies rules for valid data
sanitation: cleans up data, by removing unwanted characters etc

51
Q

Mongoose: How to make a field required?

A

required: true

52
Q

Mongoose: how to validate input?

A
validate(value){
      if(value < 21){
           throw new Error("Not old enough")
      }
}
53
Q

Which npm package can we use for validation?

A

npm validator

54
Q

Mongoose: String sanitation

A

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

55
Q

Mongoose: number sanitation

A

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.

56
Q

Mongoose: How to set default on models?

A

default: “SomeDefaultValue”

57
Q

What should be done before data is entered into a database?

A

The data should be validated and sanitized.

58
Q

Mongoose: When defining the model, how can we check wether a value includes a specific expression?

A
validate(value){
    if(value.includes("phrase"){
        //do something
    }
}