#TernopilJS

MeteorJS

Лекція 7. MongoDB

Лектор - Михайло

Код - github.com/ternopiljs

Презентації - slides.com/ternopiljs

Новини - vk.com/ternopiljs

  • MongoDB

  • MongoDB shell

  • CRUD операції

  • MongoBD оператори

  • Курсор

  • Повнотекстовий пошук

  • Meteor MongoDB API

  • open source
  • scalable
  • high-performance
  • schema-free
  • document-oriented

...NoSQL database

Horizontal

Scaling

Vertical

Schema-free

// User documents
{
    _id: 'vYBRbWWqTJkYSw6H9',
    username: 'mike',
    services: {
        twitter: {
            accessToken: '<access token>',
            username: 'mike123'   
        }
    },
    createdAt: <Date>
},
{
    _id: 'vYBRbWWqTJkYSw6H9',
    username: 'andy',
    services: {
        github: {
            accessToken: '<access token>',
            username: 'andy123'   
        },
        instagram: {
            accessToken: '<access token>',
            username: 'andy123'  
        }
    },
    createdAt: <Date>
}

Schema validation

aldeed:collection2

var Schemas = {};

Schemas.Book = new SimpleSchema({
    title: {
        type: String,
        label: "Title",
        max: 200
    },
    author: {
        type: String,
        label: "Author"
    },
    copies: {
        type: Number,
        label: "Number of copies",
        min: 0,
        optional: true
    },
});

Books.attachSchema(Schemas.Book);

Зв'язки

> meteor mongo

Mongo shell

> db.stats() // інформація про БД
> db.createCollection(<name>, <options>) // створити колекцію
> db.<name>.stats() // інформація про колекцію
> db.<name>.find().explain() // інформація про курсор
Collection = new Mongo.Collection(<name>)

Insert

> db.posts.insert({field1: value1, field2: value2})

CRUD операції

Delete

> db.posts.remove({}) // remove all documents from the collection
> db.posts.remove({field1: value1})
Posts.insert({field1: value1, field2: value2})
Posts.remove({}) // remove all documents from the collection
Posts.remove({field1: value1})

Read

> db.posts.find({field1: value1, field2: value2})

CRUD операції

{field1: value1, field2: value2} // еквівалент оператора "І" (AND)
> db.posts.find({$or: [{field1: value1}, {field2: value2}]})
{$or: [{field1: value1}, {field2: value2}]} // "АБО" (OR)
Posts.find({field1: value1, field2: value2})
Posts.find({$or: [{field1: value1}, {field2: value2}]})

Read

CRUD операції

$lt$lte$gt$gte, $ne - додаткові оператори mongodb

db.posts.find({type: {$ne: 'question'}}); 
db.posts.find({rating: {$gt: 100}}); 
Posts.find({type: {$ne: 'question'}}); 
Posts.find({rating: {$gt: 100}}); 

Update

CRUD операції

db.posts.update({_id: 'XgQvqZAqwPxQPAJjo'}, {title: 'New post', type: 'question'}); 
{
    _id: 'XgQvqZAqwPxQPAJjo',
    title: 'Old post',
}
{
    _id: 'XgQvqZAqwPxQPAJjo',
    title: 'New post',
    type: 'question'
}
Posts.update({_id: 'XgQvqZAqwPxQPAJjo'}, {title: 'New post', type: 'question'}); 

Update

CRUD операції

db.posts.update({_id: 'XgQvqZAqwPxQPAJjo'}, {$set: {type: 'question'}})
{
    _id: 'XgQvqZAqwPxQPAJjo',
    title: 'Old post',
}
{
    _id: 'XgQvqZAqwPxQPAJjo',
    title: 'Old post',
    type: 'question'
}

модифікатор $set

Posts.update({_id: 'XgQvqZAqwPxQPAJjo'}, {$set: {type: 'question'}})

Update

CRUD операції

db.posts.update({_id: 'XgQvqZAqwPxQPAJjo'}, {$inc: {rating: 1}})
{
    _id: 'XgQvqZAqwPxQPAJjo',
    title: 'Old post',
    rating: 1
}
{
    _id: 'XgQvqZAqwPxQPAJjo',
    title: 'Old post',
    rating: 2
}

модифікатор $inc

Posts.update({_id: 'XgQvqZAqwPxQPAJjo'}, {$inc: {rating: 1}})

Update

CRUD операції

модифікатор $push

db.posts.update({_id: 'XgQvqZAqwPxQPAJjo'}, {$push: {tags: 'js'}})
{
    _id: 'XgQvqZAqwPxQPAJjo',
    title: 'Old post',
    tags: ['mongodb']
}
{
    _id: 'XgQvqZAqwPxQPAJjo',
    title: 'Old post',
    tags: ['mongodb', 'js']
}
Posts.update({_id: 'XgQvqZAqwPxQPAJjo'}, {$push: {tags: 'js'}})

Update

CRUD операції

upsert

db.posts.update({title: 'New post'}, {$push: {tags: 'js'}}, {upsert: true})
not found
{
    _id: 'XgQvqZAqwPxQPAJjo',
    title: 'Old post',
    tags: ['js']
}
Posts.upsert({title: 'New post'}, {$push: {tags: 'js'}})

Update

CRUD операції

множинне обновлення 

db.posts.update({type: 'question'}, {$set: {type: 'quote'}}, {multi: true})
{
    _id: "LAE7H52DnuRFe7cr4",
    type: 'question',
    title: 'What does null mean?'
},
{
    _id: "hAph8hBnCofeMme5K",
    type: 'question',
    title: 'What does the fox say?'
},
{
    _id: "S3FQxTjKTLRQPyhRB",
    type: 'question',
    title: 'What does what mean?'
}
{
    _id: "LAE7H52DnuRFe7cr4",
    type: 'quote',
    title: 'What does null mean?'
},
{
    _id: "hAph8hBnCofeMme5K",
    type: 'quote',
    title: 'What does the fox say?'
},
{
    _id: "S3FQxTjKTLRQPyhRB",
    type: 'quote',
    title: 'What does what mean?'
}
Posts.update({type: 'question'}, {$set: {type: 'quote'}}, {multi: true})

.find()

db.posts.find({type: 'question'}, {title: 1})
{
    _id: "LAE7H52DnuRFe7cr4",
    type: 'question',
    title: 'What does null mean?'
},
{
    _id: "hAph8hBnCofeMme5K",
    type: 'question',
    title: 'What does the fox say?'
},
{
    _id: "S3FQxTjKTLRQPyhRB",
    type: 'question',
    title: 'What does what mean?'
}

Вибір полів

{
    _id: "LAE7H52DnuRFe7cr4",
    title: 'What does null mean?'
},
{
    _id: "hAph8hBnCofeMme5K",
    title: 'What does the fox say?'
},
{
    _id: "S3FQxTjKTLRQPyhRB",
    title: 'What does what mean?'
}
Posts.find({type: 'question'}, {fields: {title: 1}})

.find()

db.posts.find({type: 'question'}).sort({title: 1})
{
    _id: "LAE7H52DnuRFe7cr4",
    type: 'question',
    title: 'The question'
},
{
    _id: "hAph8hBnCofeMme5K",
    type: 'question',
    title: 'A question'
},
{
    _id: "S3FQxTjKTLRQPyhRB",
    type: 'question',
    title: 'Question'
}

Сортування

{
    _id: "LAE7H52DnuRFe7cr4",
    type: 'question',
    title: 'A question'
},
{
    _id: "hAph8hBnCofeMme5K",
    type: 'question',
    title: 'Question'
},
{
    _id: "S3FQxTjKTLRQPyhRB",
    type: 'question',
    title: 'The question'
}
db.posts.find({type: 'question'}, {sort: {title: 1}})

.find()

db.posts.find({type: 'question'}).limit(2).skip(1)
{
    _id: "LAE7H52DnuRFe7cr4",
    type: 'question',
    title: 'The question'
},
{
    _id: "hAph8hBnCofeMme5K",
    type: 'question',
    title: 'A question'
},
{
    _id: "S3FQxTjKTLRQPyhRB",
    type: 'question',
    title: 'Question'
}

Ліміт, пропуск елементів

{
    _id: "hAph8hBnCofeMme5K",
    type: 'question',
    title: 'A question'
},
{
    _id: "S3FQxTjKTLRQPyhRB",
    type: 'question',
    title: 'Question'
}
Posts.find({type: 'question'}, {limit: 2, skip: 1})

.find()

db.posts.find({type: 'question'}).count()
{
    _id: "LAE7H52DnuRFe7cr4",
    type: 'question',
    title: 'The question'
},
{
    _id: "hAph8hBnCofeMme5K",
    type: 'question',
    title: 'A question'
},
{
    _id: "S3FQxTjKTLRQPyhRB",
    type: 'question',
    title: 'Question'
}

.count()

> 3

.count()

Posts.find({type: 'question'}).count()

.find()

db.posts.find({type: 'question'}).toArray()
{
    _id: "LAE7H52DnuRFe7cr4",
    type: 'question',
    title: 'The question'
},
{
    _id: "hAph8hBnCofeMme5K",
    type: 'question',
    title: 'A question'
},
{
    _id: "S3FQxTjKTLRQPyhRB",
    type: 'question',
    title: 'Question'
}

.toArray()

[{
    _id: "LAE7H52DnuRFe7cr4",
    type: 'question',
    title: 'The question'
},
{
    _id: "hAph8hBnCofeMme5K",
    type: 'question',
    title: 'A question'
},
{
    _id: "S3FQxTjKTLRQPyhRB",
    type: 'question',
    title: 'Question'
}]

.fetch()

Posts.find({type: 'question'}).fetch()

Індекси

db.posts.createIndex({category: 1, userId: 1}) // створення індекса
db.posts.dropIndex({category: 1, userId: 1}) // видалення індекса
db.posts.createIndex({title: 1}, {unique: true}) // створення унікального індекса
Posts._ensureIndex({category: 1, userId: 1})
Posts._ensureIndex({title: 1}, {unique: true})
Posts._dropIndex({category: 1, userId: 1})

Повнотекстовий пошук

db.posts.find({$text: {$search: "coffee"}}) // Пошук документів
db.posts.createIndex({content: 'text'}) // створення індекса
Posts._ensureIndex({content: 'text'})
Posts.find({$text: {$search: "coffee"}})

Повнотекстовий пошук

  • Publish/Subscribe
  • Allow/Deny rules
  • Observers

У наступній лекції:

?

Lecture #7 - MongoDB

By ternopiljs

Lecture #7 - MongoDB

  • 957