Учебники

1) Что такое MongoDB?

Что такое MongoDB?

MongoDB — это документно-ориентированная база данных NoSQL, используемая для хранения больших объемов данных. Вместо использования таблиц и строк, как в традиционных реляционных базах данных, MongoDB использует коллекции и документы. Документы состоят из пар ключ-значение, которые являются основной единицей данных в MongoDB. Коллекции содержат наборы документов и функции, которые эквивалентны таблицам реляционной базы данных. MongoDB — это база данных, появившаяся в середине 2000-х годов.

В этом уроке вы узнаете

Особенности MongoDB

    1. Каждая база данных содержит коллекции, которые в свою очередь содержат документы. Каждый документ может быть разным с различным количеством полей. Размер и содержание каждого документа могут отличаться друг от друга.
    2. Структура документа больше соответствует тому, как разработчики конструируют свои классы и объекты на соответствующих языках программирования. Разработчики часто говорят, что их классы не являются строками и столбцами, а имеют четкую структуру с парами ключ-значение.
    3. Строки (или документы, вызываемые в MongoDB) не обязательно должны иметь заранее определенную схему. Вместо этого поля могут быть созданы на лету.
    4. Модель данных, доступная в MongoDB, позволяет вам представлять иерархические отношения, проще хранить массивы и другие более сложные структуры.
  1. Масштабируемость — среды MongoDB очень масштабируемы. Компании по всему миру определили кластеры, причем некоторые из них имеют более 100 узлов с миллионами документов в базе данных.

Пример MongoDB

В приведенном ниже примере показано, как можно смоделировать документ в MongoDB.

  1. Поле _id добавлено MongoDB для уникальной идентификации документа в коллекции.
  2. Следует отметить, что данные заказа (OrderID, Product и Количество), которые в СУБД обычно хранятся в отдельной таблице, тогда как в MongoDB они фактически хранятся в виде встроенного документа в самой коллекции. Это одно из ключевых отличий в том, как моделируются данные в MongoDB.

MongoDB Учебник для начинающих

Ключевые компоненты архитектуры MongoDB

Ниже приведены несколько общих терминов, используемых в MongoDB.

  1. _id – This is a field required in every MongoDB document. The _id field represents a unique value in the MongoDB document. The _id field is like the document’s primary key. If you create a new document without an _id field, MongoDB will automatically create the field. So for example, if we see the example of the above customer table, Mongo DB will add a 24 digit unique identifier to each document in the collection.
_Id CustomerID CustomerName OrderID
563479cc8a8a4246bd27d784 11 Guru99 111
563479cc7a8a4246bd47d784 22 Trevor Smith 222
563479cc9a8a4246bd57d784 33 Nicole 333
  1. Collection – This is a grouping of MongoDB documents. A collection is the equivalent of a table which is created in any other RDMS such as Oracle or MS SQL. A collection exists within a single database. As seen from the introduction collections don’t enforce any sort of structure.
  2. Cursor – This is a pointer to the result set of a query. Clients can iterate through a cursor to retrieve results.
  3. Database – This is a container for collections like in RDMS wherein it is a container for tables. Each database gets its own set of files on the file system. A MongoDB server can store multiple databases.
  4. Document — A record in a MongoDB collection is basically called a document. The document, in turn, will consist of field name and values.
  5. Field — A name-value pair in a document. A document has zero or more fields. Fields are analogous to columns in relational databases.

    The following diagram shows an example of Fields with Key value pairs. So in the example below CustomerID and 11 is one of the key value pair’s defined in the document.

MongoDB Учебник для начинающих

  1. JSON – This is known as JavaScript Object Notation. This is a human-readable, plain text format for expressing structured data. JSON is currently supported in many programming languages.

Just a quick note on the key difference between the _id field and a normal collection field. The _id field is used to uniquely identify the documents in a collection and is automatically added by MongoDB when the collection is created.

Why Use MongoDB?

Below are the few of the reasons as to why one should start using MongoDB

  1. Document-oriented – Since MongoDB is a NoSQL type database, instead of having data in a relational type format, it stores the data in documents. This makes MongoDB very flexible and adaptable to real business world situation and requirements.
  2. Ad hoc queries — MongoDB supports searching by field, range queries, and regular expression searches. Queries can be made to return specific fields within documents.
  3. Indexing — Indexes can be created to improve the performance of searches within MongoDB. Any field in a MongoDB document can be indexed.
  4. Replication — MongoDB can provide high availability with replica sets. A replica set consists of two or more mongo DB instances. Each replica set member may act in the role of the primary or secondary replica at any time. The primary replica is the main server which interacts with the client and performs all the read/write operations. The Secondary replicas maintain a copy of the data of the primary using built-in replication. When a primary replica fails, the replica set automatically switches over to the secondary and then it becomes the primary server.
  5. Load balancing — MongoDB uses the concept of sharding to scale horizontally by splitting data across multiple MongoDB instances. MongoDB can run over multiple servers, balancing the load and/or duplicating data to keep the system up and running in case of hardware failure.

Data Modelling in MongoDB

As we have seen from the Introduction section, the data in MongoDB has a flexible schema. Unlike in SQL databases, where you must have a table’s schema declared before inserting data, MongoDB’s collections do not enforce document structure. This sort of flexibility is what makes MongoDB so powerful.

When modeling data in Mongo, keep the following things in mind

  1. What are the needs of the application – Look at the business needs of the application and see what data and the type of data needed for the application. Based on this, ensure that the structure of the document is decided accordingly.
  2. What are data retrieval patterns – If you foresee a heavy query usage then consider the use of indexes in your data model to improve the efficiency of queries.
  3. Частые вставки, обновления и удаления происходят в базе данных? Пересмотрите использование индексов или включите сегментирование, если это необходимо, в ваш дизайн моделирования данных, чтобы повысить эффективность всей среды MongoDB.

Разница между MongoDB и RDBMS

Ниже приведены некоторые ключевые различия между MongoDB и RDBMS.

RDBMS
MongoDB
разница
Таблица Коллекция В RDBMS таблица содержит столбцы и строки, которые используются для хранения данных, тогда как в MongoDB эта же структура называется коллекцией. Коллекция содержит документы, которые, в свою очередь, содержат поля, которые в свою очередь являются парами ключ-значение.
Строка Документ В СУБД строка представляет собой один неявно структурированный элемент данных в таблице. В MongoDB данные хранятся в документах.
колонка поле В СУБД столбец обозначает набор значений данных. Они в MongoDB известны как поля.
присоединяется Встроенные документы В СУБД данные иногда распределяются по разным таблицам, и для полного представления всех данных иногда создается соединение по таблицам для получения данных. В MongoDB данные обычно хранятся в одной коллекции, но разделяются с помощью встроенных документов. Так что в MongoDB нет концепции объединений.

Помимо различий в терминах, несколько других различий показаны ниже

  1. Реляционные базы данных известны обеспечением целостности данных. Это не является явным требованием в MongoDB.
  2. СУБД требует, чтобы данные сначала были нормализованы, чтобы предотвратить потерю записей и дублирование. Для нормализации данных требуется больше таблиц, что приведет к большему количеству объединений таблиц, что потребует большего количества ключей и индексов.

    Поскольку базы данных начинают расти, производительность может стать проблемой. Опять же, это не является явным требованием в MongoDB. MongoDB является гибким и не нуждается в нормализации данных в первую очередь.