Как обновить mongo ubuntu

Обновлено: 05.07.2024

В данной статье рассмотрим, как реплицировать и обновить MongoDB на Ubuntu 18.04.

Примечание

О конфигурации оборудования, а также о том, как установить и настроить MongoDB, читайте тут.

В описании далее используем следующие имена и IP-адреса серверов:

Настройка ReplicaSet MongoDB

Replicaset - это несколько серверов, которые содержат один и тот же набор данных, обеспечивают защиту от сбоев и высокую доступность данных. В Replicaset MongoDB есть одна primary нода для записи и чтения и одна или несколько secondary нод, синхронизированных с primary нодой и предоставляющих возможность чтения данных для снижения нагрузки. В случае сбоя в работе primary ноды одна из secondary нод автоматически назначается primary нодой. Для ускорения выбора новой primary ноды предназначена нода - арбитр, которая не содержит данных. Также преимуществом Replicaset является возможность обновления кластера без необходимости останова его работы.

Replicaset инициализирован, нода находится в состоянии primary.

Как видим, вторая нода с _id=1 принята в Repliset в состоянии secondary.

При добавлении ноды в replicaset происходит синхронизация c primary ноды. Пока синхронизация не завершена, вторая нода будет находиться в состоянии STARTUP. Запись данных на основную ноду замедляет синхронизацию, однако, это возможный сценарий (например, при записи в базу база размером около 350 ГБ синхронизировалась около 14 часов).

Как только синхронизация будет завершена, на третьем сервере (mongoar) выполните то же, что и на втором (mongo2), кроме шага добавления сервера в repliset:

Проверьте состояние Repliset (для краткости из вывода выброшено несущественное):

В результате мы получили primary ноду, secondary ноду и arbiter ноду. Repliset синхронизирован и находится в работоспособном состоянии.

Обновление Replicaset MongoDB

Рассмотрим обновление на примере перехода с версии 4.0 на версию 4.2. Чтобы понимать, какие изменения могут привести к неработоспособности текущей схемы данных, ознакомьтесь с документом.

  1. Измените параметр feature compatibility version, ограничивающий версию MongoDB, которую можно использовать с текущим набором данных. Для обновления с версии 4.0 на версию 4.2 установите его в 4.0:
  1. Проверьте результат:
  1. На всех трех серверах подключите репозиторий с новой версией MongoDB (пример для первого сервера):
  1. Исходя из документации, в конфигурационный файл /etc/mongod.conf добавьте опцию enableMajorityReadConcern: false и замените net:ssl на net:tls (пример для арбитра):
  1. Обновите ноду арбитра:
  1. Проверьте статус rs.status(). Убедитесь, что арбитр работает, и посмотрите, какая из двух оставшихся нод является secondary (вывод команды сокращен):
  1. В текущий момент сервер mongo2 является secondary, обновите MongoDB на нем:
  1. Посмотрите rs.status(), убедитесь, что нода работает:
  1. Принудительно измените primary ноду на ту, которую уже обновили (в нашем случае - mongo2):
  1. Теперь нода mongo1 стала secondary, обновите ее по аналогии с предыдущей.
  2. Проверьте состояние replicaset после обновления (вывод сокращен):

Все выполнено успешно. Если есть необходимость сохранения порядка нод, который был до обновления, зайдите в консоль текущей primary ноды (mongo2) и выполните команду:

Нода станет secondary, primary нодой станет mongo1, как и было до обновления.

Мы выполнили обновление без вывода кластера из работы, то есть бесшовно.

В случае обновления одиночного сервера MongoDB обновите параметр feature compatibility version, подключите репозиторий с новой версией mongodb , поправьте конфигурационный файл сервера и обновите сервер mongodb на новую версию, как описано выше. В этом случае потребуется останов сервера.

Возникли проблемы или остались вопросы? Напишите нам, мы будем рады вам помочь.

The following steps outline the procedure to upgrade a standalone mongod from version 4.0 to 4.2 .

Before you attempt any upgrade, please familiarize yourself with the content of this document.

If you need guidance on upgrading to 4.2 , MongoDB offers major version upgrade services to help ensure a smooth transition without interruption to your MongoDB application.

Upgrade Recommendations and Checklists¶

When upgrading, consider the following:

Upgrade Version Path¶

To upgrade an existing MongoDB deployment to 4.2 , you must be running a 4.0-series release.

To upgrade from a version earlier than the 4.0-series , you must successively upgrade major releases until you have upgraded to 4.0-series . For example, if you are running a 3.6-series , you must upgrade first to 4.0 before you can upgrade to 4.2 .

Check Driver Compatibility¶

Upgraded deployments that run on incompatible drivers might encounter unexpected or undefined behavior.

Preparedness¶

Before beginning your upgrade, see the Compatibility Changes in MongoDB 4.2 document to ensure that your applications and deployments are compatible with MongoDB 4.2 . Resolve the incompatibilities in your deployment before starting the upgrade.

Before upgrading MongoDB, always test your application in a staging environment before deploying the upgrade to your production environment.

Downgrade Consideration¶

Once upgraded to

, if you need to downgrade, we recommend

to the latest patch release of

Prerequisites¶

MMAPv1 to WiredTiger Storage Engine¶

MongoDB 4.2 removes support for the deprecated MMAPv1 storage engine.

If your 4.0 deployment uses MMAPv1, you must change the 4.0 deployment to WiredTiger Storage Engine before upgrading to MongoDB 4.2. For details, see Change Standalone to WiredTiger.

Review Current Configuration¶

With MongoDB 4.2, the mongod and mongos processes will not start with MMAPv1 Specific Configuration Options. Previous versions of MongoDB running WiredTiger ignored MMAPv1 configurations options if they were specified. With MongoDB 4.2, you must remove these from your configuration.

Feature Compatibility Version¶

The 4.0 instance must have featureCompatibilityVersion set to 4.0 . To check featureCompatibilityVersion :

The operation should return a result that includes "featureCompatibilityVersion" : < "version" : "4.0" >.

To set or update featureCompatibilityVersion , run the following command:

Download 4.2 Binaries¶

Via Package Manager¶

If you installed MongoDB from the MongoDB apt , yum , dnf , or zypper repositories, you should upgrade to 4.2 using your package manager.

Follow the appropriate 4.2 installation instructions for your Linux system. This will involve adding a repository for the new release, then performing the actual upgrade process.

Manually¶

If you have not installed MongoDB using a package manager, you can manually download the MongoDB binaries from the MongoDB Download Center.

Upgrade Process¶

Replace existing 4.0 binaries with the 4.2 binaries.¶

Shut down your mongod instance. Replace the existing binary with the 4.2 mongod binary.

Restart your deployment with the 4.2 mongod .

Enable backwards-incompatible 4.2 features.¶

At this point, you can run the 4.2 binaries without the 4.2 features that are incompatible with 4.0 .

To enable these 4.2 features, set the feature compatibility version ( FCV ) to 4.2 .

Enabling these backwards-incompatible features can complicate the downgrade process since you must remove any persisted backwards-incompatible features before you downgrade.

It is recommended that after upgrading, you allow your deployment to run without enabling these features for a burn-in period to ensure the likelihood of downgrade is minimal. When you are confident that the likelihood of downgrade is minimal, enable these features.

Run the setFeatureCompatibilityVersion command against the admin database:

This command must perform writes to an internal system collection. If for any reason the command does not complete successfully, you can safely retry the command as the operation is idempotent.

MongoDB versioning have the form X.Y.Z where Z refers to the revision/patch number. Revisions provide security patches, bug fixes, and new or changed features that generally do not contain any backward breaking changes. Always upgrade to the latest revision in your release series.

For more information on versioning, see MongoDB Versioning.

Before Upgrading¶

Backup¶

Ensure you have an up-to-date backup of your data set. See MongoDB Backup Methods.

Compatibility Considerations¶

Consult the following documents for any special considerations or compatibility issues specific to your MongoDB release:

  • Starting in MongODB 4.2, MongoDB removes support for Ubuntu 16.04 PPCLE.
  • Starting in MongoDB 3.6.13, MongoDB 3.6-series removes support for Ubuntu 16.04 PPCLE.
  • Starting in MongoDB 3.4.21, MongoDB 3.4-series removes support for Ubuntu 16.04 PPCLE.

Maintenance Window¶

If your installation includes replica sets, plan the upgrade during a predefined maintenance window.

Change Streams¶

Starting in MongoDB 4.0.7, change streams use a version 1 v1 resume tokens. MongoDB versions earlier than 4.0.7 use v0 resume tokens.

When upgrading from MongoDB 4.0.6 or earlier to MongoDB 4.0.7 or later, a client may try to resume change streams using the new v1 resume token when connected to a member that has not been updated (i.e. only accepts v0 or BinData token) and fail. In such cases, the client must wait for the upgrade to complete before resuming change streams.

Staging Environment Check¶

Before you upgrade a production environment, use the procedures in this document to upgrade a staging environment that reproduces your production environment, to ensure that your production configuration is compatible with all changes.

Upgrade Procedure¶

Always backup all of your data before upgrading MongoDB.

Upgrade each mongod and mongos binary separately, using the procedure described here. When upgrading a binary, use the procedure Upgrade a MongoDB Instance.

  1. For deployments that use authentication, first upgrade all of your MongoDB Drivers. To upgrade, see the documentation for your driver.
  2. Upgrade sharded clusters, as described in Upgrade Sharded Clusters.
  3. Upgrade any standalone instances. See Upgrade a MongoDB Instance.
  4. Upgrade any replica sets that are not part of a sharded cluster, as described in Upgrade Replica Sets.

Upgrade a MongoDB Instance¶

To upgrade a mongod or mongos instance, use one of these approaches:

Replace the Existing Binaries¶

Always backup all of your data before upgrading MongoDB.

To upgrade a mongod or mongos instance by replacing the existing binaries:

  1. Download the binaries for the latest MongoDB revision from the MongoDB Download Page and store the binaries in a temporary location. The binaries download as compressed files that uncompress to the directory structure used by the MongoDB installation.
  2. Shutdown the instance.
  3. Replace the existing MongoDB binaries with the downloaded binaries.
  4. Make any required configuration file changes.
  5. Restart the instance.

Upgrade Replica Sets¶

To upgrade a replica set, upgrade each member individually, starting with the secondaries and finishing with the primary. Plan the upgrade during a predefined maintenance window.

Before you upgrade or downgrade a replica set, ensure all replica set members are running. If you do not, the upgrade or downgrade will not complete until all members are started.

Starting in MongoDB 4.0.7, change streams use a version 1 v1 resume tokens. MongoDB versions earlier than 4.0.7 use v0 resume tokens or BinData resume tokens.

When upgrading from MongoDB 4.0.0-4.0.6 to MongoDB 4.0.7 or later, a client may try to resume change streams using the new v1 resume token when connected to a member that has not been updated (i.e. only accepts v0 token or BinData) and fail. In such cases, the client must wait for the upgrade to complete before resuming change streams.

Upgrade Secondaries¶

Upgrade each secondary separately as follows:

The secondary may briefly go into STARTUP2 or RECOVERING . This is normal. Make sure to wait for the secondary to fully recover to SECONDARY before you continue the upgrade.

Upgrade the Primary¶

Step down the primary to initiate the normal failover procedure. Using one of the following:

  • The rs.stepDown() helper in mongosh .
  • The replSetStepDown database command.

During failover, the set cannot accept writes. Typically this takes 10-20 seconds. Plan the upgrade during a predefined maintenance window.

Stepping down the primary is preferable to directly shutting down the primary. Stepping down expedites the failover procedure.

Upgrade Sharded Clusters¶

Changed in version 3.4: The procedure applies to 5.0 . To make revision upgrades for other versions of MongoDB sharded clusters, refer to the appropriate version of the manual.

Starting in MongoDB 4.0.7, change streams use a version 1 v1 resume tokens. MongoDB versions earlier than 4.0.7 use v0 resume tokens or BinData resume tokens.

When upgrading from MongoDB 4.0.6 or earlier to 4.0.7 or later, the members of the sharded clusters will continue to produce v0 or BinData resume tokens until the mongos instance(s) are updated. Upgraded mongos instances will begin producing v1 change stream resume tokens. These tokens cannot be used to resume a stream on a mongos that has not yet been upgraded to 4.0.7 or later.

To upgrade a 5.0 sharded cluster:

To upgrade the config server replica set, use the procedures in Upgrade Replica Sets.

В данной статье рассмотрим, как установить и настроить Standalone MongoDB на Ubuntu 18.04.

Примечание.

В описании далее используем следующие имена и IP-адреса серверов:

Конфигурация оборудования

Рассмотрим установку MongoDB версии 4.0. Для сервера MongoDB нам потребуются три сервера Ubuntu 18.04 LTS x86_64.

Можно установить одиночный сервер MongoDB. Если необходимо установить replicaset MongoDB, нужно минимум три сервера: два - для primary и secondary, еще один - для арбитра (подробнее и настройке читайте тут). Мощности серверов primary и secondary выбираются, исходя из емкости и нагруженности базы данных, сервер арбитра требует минимум ресурсов.

Для хранения данных MongoDB рекомендует использовать файловую систему XFS, поэтому желательно подключить отдельный том XFS (подробнее см. читайте тут).

В качестве языка консоли MongoDB используется JavaScript.

**Как сэкономить время на установке MongoDB

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

Преимущества MongoDB

MongoDB (от англ. humongous — огромный) — документоориентированная система управления базами данных (СУБД) с открытым исходным кодом, не требующая описания схемы таблиц. MongoDB классифицирована как NoSQL, использует JSON-подобные документы и схему базы данных, написана на языке C++ (подробнее см. тут).

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

Установка Standalone MongoDB

Внимание

В поле CommonName укажите имя сервера (hostname).

  1. Сгенерируйте клиентский сертификат, который будет использоваться для mongo-консоли (см. предыдущий шаг), и поместите его в папку /etc/ssl/client.pem.
  2. В текстовом редакторе откройте конфигурационный файл /etc/mongod.conf и приведите его к следующему виду:

Внимание

  • bindIp указывает, по каким адресам будет доступен Mongod. Если указано 0.0.0.0, сервер слушает все интерфейсы. Если нужен только локальный доступ, вместо 0.0.0.0 укажите localhost.
  • dbPath указывает путь к базе данных. Рекомендуемая файловая система хранилища - XFS.
  1. Запустите Mongod и добавьте его в список приложений, загружаемых автоматически:
  1. Проверьте соединение с сервером:
  1. В консоли mongo создайте пользователя admin с правами для создания других пользователей:

Чтобы выйти из консоли, нажмите Ctrl+D.

  1. Отредактируйте конфигурационный файл /etc/mongod.conf, раскомментируйте секцию security и добавьте опцию authorization: enabled :
  1. Перезапустите сервер mongod:
  1. Проверьте соединение:

Пример создания дополнительного пользователя с правами чтения/записи на коллекцию test и чтения на коллекцию reporting:

Кроме того, MongoDB версии 4 содержит встроенный мониторинг, который можно включить в консоли следующей командой:

В результате вы получите URL для просмотра метрик сервера.

Примечание

Как настроить репликацию и обновление MongoDB, читайте тут.

Обратная связь

Возникли проблемы или остались вопросы? Напишите нам, мы будем рады вам помочь.

Читайте также: