├── course ├── auth.js ├── client │ └── index.js ├── collections │ └── collection.js ├── create.js ├── crud │ └── crud.js ├── database │ └── index.js ├── document │ ├── document.js │ ├── news.js │ ├── noticias.sql │ └── readme.md ├── person.json ├── readme.md └── shell │ └── index.js ├── first-db.js └── readme.md /course/auth.js: -------------------------------------------------------------------------------- 1 | // create a new user 2 | db.createUser({ 3 | user:'fazt', 4 | pwd: '1234', 5 | roles: ["readWrite", "dbAdmin"] 6 | }); 7 | 8 | // login with a user 9 | use databasename; 10 | 11 | db.auth("fazt", "1234"); 12 | -------------------------------------------------------------------------------- /course/client/index.js: -------------------------------------------------------------------------------- 1 | // the client is the mongo shell 2 | 3 | // to watch all databases 4 | show dbs 5 | 6 | // to see current databse selected 7 | db 8 | 9 | // to select or create a database 10 | use mivirtualstore 11 | 12 | // CRUD OPERATIONS 13 | // TO CREATE 14 | 15 | const post = { 16 | "title": "My first Post", 17 | "content": "Here is my blog post", 18 | "date": new Date() 19 | } 20 | // this generates an _id 21 | db.blog.insert(post) // WriteResult({ "nInserted" : 1 }) 22 | 23 | // TO READ 24 | db.posts.find() // to query all collections 25 | db.posts.findOne() // to query a single collection 26 | 27 | // TO UPDATE 28 | // we need (criteria, newDocument) 29 | const myNewPost = db.posts.findOne() 30 | myNewPost.comments = []; 31 | db.posts.update( 32 | {_id: ObjectId("5a2490f249c2a502853b7e7a")}, 33 | myNewPost 34 | ) // this add comments: [] 35 | 36 | // TO REMOVE 37 | db.posts.remove({title: "My first Post"}) 38 | -------------------------------------------------------------------------------- /course/collections/collection.js: -------------------------------------------------------------------------------- 1 | // create a collection 2 | db.createCollection('articles'); 3 | 4 | // to delete a collection 5 | db.articles.drop(); 6 | 7 | // have DYNAMIC SQUEMAS 8 | // means the documents can be different inside of a collection 9 | // for example this could be stored in a single collection 10 | {"greeting": "Hello World"} 11 | {"foo": 5} 12 | 13 | // so why we need to separate collections 14 | // Keeping different kinds of documents in the same collection can be a nightmare 15 | // we need to make sure that each query is only returning documents of a certain type or that the application code performing a 16 | // • It is much faster to get a list of collections than to extract a list of the types in a collection. For example, if we had a "type" field in each document that specified whether the document was a “skim,” “whole,” or “chunky monkey,” it would be much 17 | // slower to find those three values in a single collection than to have three separate collections and query the correct collection. 18 | // • Grouping documents of the same kind together in the same collection allows for 19 | // data locality. Getting several blog posts from a collection containing only posts will 20 | // likely require fewer disk seeks than getting the same posts from a collection con‐ 21 | // taining posts and author data. 22 | // • We begin to impose some structure on our documents when we create indexes. 23 | // (This is especially true in the case of unique indexes.) These indexes are defined per 24 | // collection. By putting only documents of a single type into the same collection, we 25 | // can index our collections more efficiently. 26 | 27 | // these documents have diferent keys and value types 28 | 29 | // callection restrictions are: 30 | // empy string "" is not valid as a name collection 31 | // collection names may not be contain \0 32 | // no create collection that start with: symstem. (it's reserved for internal collections) 33 | // not use $ as a name 34 | 35 | // SUBCOLLECTIONS 36 | // usefull to separated by names 37 | blog.posts 38 | blog.users 39 | // these are different collections, and just used 40 | // with organizational purpouse 41 | // also usefull for GRIDFS nad drivers 42 | -------------------------------------------------------------------------------- /course/create.js: -------------------------------------------------------------------------------- 1 | db.customers.insert({ 2 | "first_name": "Aaron", 3 | "last_name": "Swartz" 4 | }); 5 | -------------------------------------------------------------------------------- /course/crud/crud.js: -------------------------------------------------------------------------------- 1 | // INSERT A NEW DOCUMENT 2 | db.customers.insert({ 3 | "first_name": "Aaron", 4 | "last_name": "Swartz" 5 | }); 6 | 7 | db.customers.insert( 8 | {"first_name": "Aaron", "last_name":"Swartz"}, 9 | {"first_name": "Aron", "last_name": "Swartz"} 10 | ); 11 | 12 | // SAVE AN OBJECT AS DOCUMENT 13 | var articleInfo = {} 14 | articleInfo.authorName = "Ryan Ray"; 15 | articleInfo.tags = ['database', 'network', 'computing']; 16 | articleInfo.metadata = {}; 17 | articleInfo.metadata.authors = ['Ryan Ray', 'Joe McMillan'] 18 | articleInfo.metadata.description = "A new Database"; 19 | articleInfo.metadata.created = new Date(); 20 | 21 | db.articles.save(articleInfo); 22 | 23 | // to read 24 | 25 | db.customers.find({}).pretty(); 26 | 27 | // to update 28 | 29 | db.customers.update({"first_name": "Aron"}, { 30 | "first_name": "Aron", 31 | "last_name": "Swartz", 32 | gender: "male" 33 | }); 34 | 35 | // to delete 36 | -------------------------------------------------------------------------------- /course/database/index.js: -------------------------------------------------------------------------------- 1 | // to show databases 2 | show dbs 3 | 4 | // to create or use a database 5 | use blogs; 6 | 7 | // drop a database 8 | db.dropDatabase(); 9 | -------------------------------------------------------------------------------- /course/document/document.js: -------------------------------------------------------------------------------- 1 | // documents are ordered set of keys and values 2 | // is similar to map, hash or dictionary on other 3 | // languages. in javascript are objects 4 | 5 | // is the equivalent of a row in sql 6 | 7 | // this is a simple document 8 | { "greeting": "Hello world!"} 9 | 10 | //documents can be more that just one pair key:value 11 | // of javascript types as String and number 12 | {"greeting": "Hello world!", "foo": 3} 13 | 14 | // documents keys are strings 15 | // any character is allowed with few exeptions 16 | // 1. keys must not contain the character \0. that is used to signify 17 | // the end of the key 18 | // 2. the . and $ have special properties 19 | 20 | // Mongodb is type-sensitive and case sensitive 21 | {"foo": 3} 22 | {"foo": "3"} 23 | 24 | // a document can not contain a duplicate key 25 | {"greeting": "Hello world!", "greeting": "Hello Mongodb!"} 26 | 27 | // key value pairs are ordered in this way 28 | {"x": 1, "y": 2} 29 | // so don't design your schema depending on order of fields 30 | -------------------------------------------------------------------------------- /course/document/news.js: -------------------------------------------------------------------------------- 1 | /* 2 | un documento representando una noticia de un 3 | sitio social, compuesto por: 4 | - propiedades: valores 5 | - los valores tienen tipos de datos como: 6 | - numbers, string, array, date or Other Object/Document 7 | - podemos tener una estructura jerarquica customizada 8 | */ 9 | 10 | { 11 | _id: ObjectID('4bd9e8e17cefd644108961bb'), 12 | title: 'Aventuras en las Bases de Datos', 13 | url: 'http://example.com/databases.txt', 14 | author: 'Fazt', 15 | vote_count: 20, 16 | tags: ['base de datos', 'mongodb', 'indexado'], 17 | image: { 18 | url: 'http://example.com/db.jpg', 19 | caption: 'Mi imagen asombrosa', 20 | type: 'jpg', 21 | size: 12313, 22 | data: 'Binary' 23 | }, 24 | comments: [ 25 | { 26 | user: 'jesus123', 27 | text: 'articulo interesante' 28 | }, 29 | { 30 | user: 'blogger2', 31 | text: 'otro articulo relacionado que encontre e http://www.miarticle.com' 32 | } 33 | ] 34 | } 35 | 36 | /* 37 | a diferencia de una BD SQL, vemos que: 38 | - el codigo crea la estructura no la base de datos 39 | */ 40 | -------------------------------------------------------------------------------- /course/document/noticias.sql: -------------------------------------------------------------------------------- 1 | create table posts( 2 | id int(11), 3 | author_id int(11), 4 | title varchar(255), 5 | url text, 6 | vote_count smallint(5) 7 | ); 8 | 9 | create table posts_tags( 10 | id int(11), 11 | post_id int(11), 12 | tag_id int(11) 13 | ); 14 | 15 | create table tags( 16 | id int(11), 17 | text varchar(255) 18 | ); 19 | 20 | create table comments( 21 | id int(11), 22 | post_id int(11), 23 | user_id int(11), 24 | text text 25 | ); 26 | 27 | create table images( 28 | id int(11), 29 | post_id int(11), 30 | caption int(11), 31 | type varchar(255), 32 | size mediumint(8), 33 | location varchar(255) 34 | ); 35 | -------------------------------------------------------------------------------- /course/document/readme.md: -------------------------------------------------------------------------------- 1 | - document.js 2 | - diference: 3 | - news.js 4 | - news.sql 5 | -------------------------------------------------------------------------------- /course/person.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Aaron", 3 | "last_name": "Swartz", 4 | "courses": ["java", "python", "c", "javascript"], 5 | "address": { 6 | "street": "4 main street", 7 | "city": "Boston" 8 | }, 9 | "contacts": [ 10 | { 11 | "name": "Brad", 12 | "relationship": "Friend", 13 | "phone": 94654646546 14 | } 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /course/readme.md: -------------------------------------------------------------------------------- 1 | # Course 2 | - document/ 3 | - collections/ 4 | - shell/ 5 | - crud/ 6 | -------------------------------------------------------------------------------- /course/shell/index.js: -------------------------------------------------------------------------------- 1 | // to start the shell: mongo 2 | 3 | // the shell can be execute javascript 4 | x = 200; 5 | x / 5; 6 | 7 | // and we can use the standard javascript libraries 8 | Math.sin(Math.PI / 2) 9 | 10 | new Date("2018/1/1") 11 | 12 | "Hello World".replace("World, Mongodb"); 13 | 14 | // and we can define functions 15 | function factorial(n) { 16 | if (n <= 1) return 1; 17 | return n * factorial(n - 1); 18 | } 19 | 20 | const double = n => n * 2; 21 | 22 | // and the shell also recongnise incomplete statments with ENTER 23 | -------------------------------------------------------------------------------- /first-db.js: -------------------------------------------------------------------------------- 1 | show dbs 2 | 3 | use mycustomers 4 | 5 | db.createUser({ 6 | user: 'fazt', 7 | pwd: '123', 8 | roles: ['readWrite', 'dbAdmin'] 9 | }); 10 | 11 | db.createCollection('customers') 12 | 13 | show collections 14 | 15 | db.customers.insert( 16 | { 17 | firstName: 'Isaac', 18 | lastName: 'Asimov' 19 | } 20 | ) 21 | 22 | db.customers.find() 23 | .pretty() 24 | 25 | db.customers.insert( 26 | [ 27 | {firstName: 'Joe', lastName: 'MacMillan'}, 28 | {firstName: 'Elena', lastName: 'Soraya'}, 29 | {firstName: 'Isaac', lastName: 'delahaye'} 30 | ] 31 | ) 32 | 33 | db.customers.find(); 34 | db.customers.find({firstName: 'Joe'}, {firstName: true, lastName:false}); 35 | 36 | // replace or update data 37 | db.customers.update( 38 | {firstName: 'Joe'}, //query 39 | { 40 | firstName: 'Joe', 41 | lastName: 'MacMillan', 42 | gender: 'male' 43 | } // new data 44 | ); 45 | 46 | // add a new date 47 | db.customers.update( 48 | {firstName: 'Isaac'}, 49 | { 50 | $set: {gender: 'male'} 51 | } 52 | ); 53 | 54 | db.customers.update( 55 | {firstName: 'Isaac'}, 56 | { 57 | $set: {age: 45} 58 | } 59 | ); 60 | db.customers.update( 61 | {firstName: 'Isaac'}, 62 | { 63 | $inc: {age: 5} 64 | } 65 | ); 66 | 67 | db.customers.update( 68 | {firstName: 'Isaac'}, 69 | { 70 | $unset: {age: 1} 71 | } 72 | ) 73 | 74 | db.customers.update( 75 | {firstName: 'Elena'} , 76 | { 77 | firstName: 'Elena', 78 | lastName: 'Soraya' 79 | }, 80 | { upsert: true} 81 | ) 82 | 83 | db.customers.update( 84 | {firstName: 'Isaac'}, 85 | { 86 | $rename: {"gender": "sex"} 87 | } 88 | ) 89 | 90 | db.customers.remove({firstName: "Isaac"}) 91 | db.customers.remove({firstName: "Isaac"}, {justOne: true}) 92 | 93 | db.customers.find({firstName: "Elena"}); 94 | db.customers.find({$or: [{firstName: "Elena"}, {firstName: "Isaac"}]}) 95 | db.customers.fid({gender: "male"}) 96 | 97 | db.customers.find({age: {$lt: 40}}) 98 | db.customers.find({age: {$gt: 40}}) 99 | db.customers.find({age: {$gt: 30, $lt: 90}}); 100 | 101 | db.customers.find({"address.city": "Boston"}) 102 | 103 | db.customers.find({name: {$regex: 'ston'}}); 104 | 105 | // sorting 106 | db.customers.find().sort({lastName: 1}); 107 | db.customers.find().sort({lastName: -1}); 108 | db.customers.find().count() 109 | db.customers.find({gender: "male"}).count() 110 | db.customers.find().limit(4) 111 | db.customers.find().limit(4).sort({lastName: -1}) 112 | 113 | db.customers.find().forEach(function(doc) { 114 | print("Customer Name" + doc.firstName); 115 | }); 116 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ## Requiriments 2 | - Conocimientos de Javascript Básico 3 | - (Opcional) Conocimientos de JSON 4 | 5 | ## Considerations 6 | - El código estará en Ingles pero los datos en español 7 | 8 | - orientado a documentos: document 9 | 10 | ## Comandos Usuales 11 | - to show mongodb version: 'mongod --version' 12 | - to show mongodb shell version: 'mongo --version' 13 | - to show a database: `show dbs` 14 | - to create a database: `use exampledatabase` 15 | 16 | - how to create a user: `db.createUser({})` 17 | - how to login with my user: `use database`, `db.auth("user","psw")` 18 | --------------------------------------------------------------------------------