- Шпаргалка по MongoDB
- Начало работы с MongoDB
- Управление MongoDB
- Взаимодействие с базами данных MongoDB
- Взаимодействие с коллекциями MongoDB
- Взаимодействие с индексами MongoDB
- Взаимодействие с документами MongoDB
- Резервное копирование и восстановление базы данных MongoDB
- Управление ролями, пользователями и разрешениями в MongoDB
- Check the Version of Mongodb
- How to Check the Version of Mongodb
- Method # 1: Check the Mongodb Version with the Mongod Command
- Method # 2: Check the Mongodb Version with the Mongo Command
- Method # 3: Check the Mongodb Version with the File Path
- Method # 4: Check the Mongodb Version with the db.version() Command
- Method # 5: Check the Mongodb Version with the BuildInfo Parameter Command
- Method # 6: Check the Mongodb Version with the GUI Interface
- Conclusion
- About the author
- Saeed Raza
- Check MongoDB Version
- MongoDB Version when MongoDB Server is started
- MongoDB version when Mongo Shell is started
- Using db.version() command
- Conclusion
Шпаргалка по MongoDB
Мы собрали список удобных команд и запросов MongoDB и mongosh при работе с базами данных MongoDB. Пожалуйста, напишите нам @ForestAdmin, если вы хотите добавить что-то в шпаргалку!
Это второй пост из серии «Шпаргалки» после поста о PostgreSQL.
Начало работы с MongoDB
Установите MongoDB Shell mongosh
Войдите в систему и войдите в MongoDB Shell mongosh
$ mongosh //OR $ mongosh "mongodb://localhost:27017"
Вывести список баз данных MongoDB
Подключение к базе данных MongoDB
Выход из оболочки MongoDB Shell mongosh
Управление MongoDB
Проверьте, запущена ли MongoDB
Перезапуск MongoDB в Linux
db.shutdownServer() $ sudo systemctl start mongodb
Перезапуск MongoDB на Mac OSX
$ brew services stop mongodb-community@yourMongodbVersionNumber
Перезапуск MongoDB на Windows
Winkey + R Type "services.msc" Search "MondoDb" Click "restart"
Изменение пароля пользователя MongoDB
db.changeUserPassword(username, NewPassword)
Взаимодействие с базами данных MongoDB
Вывести список баз данных MongoDB
Подключение или переключение к базе данных MongoDB
Создание новой базы данных MongoDB
Показать имя текущей базы данных
Удалить базу данных MongoDB
Переименовать базу данных MongoDB
$ mongodump -d oldDatabaseName path $ mongorestore -d newDatabaseName path/oldDatabaseName.bson $ mongosh use oldDatabaseName db.dropDatabase()
Взаимодействие с коллекциями MongoDB
Описать коллекцию MongoDB
Описать все коллекции в базе данных MongoDB
Создать коллекцию MongoDB
db.createCollection("collectionName", options)
Удалить коллекцию MongoDB
Переименовать коллекцию MongoDB
db.oldCollectionName.renameCollection("newCollectionName")
Взаимодействие с индексами MongoDB
Вывести список индексов MongoDB в коллекции
db.collectionName.getIndexes()
Создание индекса MongoDB в коллекции
db.collectionName.createIndex(keys, options, commitQuorum)
Создание нескольких индексов MongoDB в коллекции
db.collectionName.createIndexes( [ keyPatterns ], options, commitQuorum )
db.collectionName.dropIndex("indexName")
Удалить все индексы в коллекции MongoDB
Перестроить индексы MongoDB
Взаимодействие с документами MongoDB
Подсчет документов в коллекции MongoDB
db.collectionName.countDocuments()
Вывести список всех документов в коллекции MongoDB
db.collectionName.find().toArray()
Создать документ в MongoDB
db.collectionName.insertOne( )
Отображение документа в MongoDB
Обновление документа в MongoDB
db.collectionName.updateOne( < "_id": documentID >, )
Удалить документ в MongoDB
db.collectionName.deleteOne(< "_id": documentID >)
Заменить документ в MongoDB
db.collectionName.replaceOne( < "_id": documentID >, )
Резервное копирование и восстановление базы данных MongoDB
Резервное копирование базы данных MongoDB
$ mongodump -d oldDatabaseName path
Восстановление базы данных MongoDB
$ mongorestore -d newDatabaseName path/oldDatabaseName.bson
Управление ролями, пользователями и разрешениями в MongoDB
Создать пользователя MongoDB
Удалить пользователя MongoDB
Изменить пароль пользователя MongoDB
db.changeUserPassword(userName, newPassword)
Вам нужно создать панель администратора или инструмент GUI для MongoDB? Посмотрите Forest Admin для MongoDB
Check the Version of Mongodb
MongoDB offers high-performance data storage when deployed over multiple servers. So, we need to identify the version of MongoDB running in the system when analyzing the reported problems. The version numbers which follow a semantic numbering scheme enable us in recognizing significant and minor changes. We can run the latest bug-free version by just updating the mongodb version which should be known. We have discussed some methods below which can be used to determine what version of MongoDB we are currently utilizing. Some of these techniques check the server version of the MongoDB, whereas others check the version of the Mongo shell.
How to Check the Version of Mongodb
The simplest approach to check the mongodb version is to run the “–help” option with the keyword “mongod”. We have opened the command line prompt in our system and placed the following command on the terminal screen of our system. The usage of this command helps us to get the flag that checks and outputs the current version of the mongodb application.
The command of “mongod –help” listed all the general options as the output which might be used for running the mongodb in our operating system. Due to the lengthy list of options, we have just shown the option “–version”. The “–version” is the option which we use along with the mongodb shell to get the mongodb version.
–networkMessageCompressors arg (=snappy,zstd,zlib)
Comma-separated list of compressors to
use for network messages
General options:
-h [ –help ] Show this usage information
–version Show version information
Method # 1: Check the Mongodb Version with the Mongod Command
Now, we can use the –version flag to get the currently installed version of the mongodb. Here, we do not have a mongodb connection as the path is not given or the mongodb shell is not opened. When we are not connected to the mongodb then we can run the command below in the command prompt of our system. The “–version” flag is used with the “mongod” command.
Once the “mongod –version” command is executed, the version of the mongodb is displayed as follows. It includes the current mongodb version and further build information on the mongodb application.
db version v6.0.3
Build Info: «version»: «6.0.3»,
«gitVersion»: «f803681c3ae19817d31958965850193de067c516»,
«modules»: [],
«allocator»: «tcmalloc»,
«environment»: «distmod»: «windows»,
«distarch»: «x86_64»,
«target_arch»: «x86_64»
>
>
Method # 2: Check the Mongodb Version with the Mongo Command
Another approach to check the mongodb version is using the mongo method. In the command prompt, we have to use the keyword “mongo” which is the shell for running the mongodb queries. The mongo is employed with the option “–version” to check the mongodb shell version. The general representation of the mongo command to fetch the version is pasted below.
The version of the mongo shell in our operating system is as follows:
mongo version v6.0.3
Build Info: «version»: «6.0.3»,
«gitVersion»: «f803681c3ae19817d31958965850193de067c516»,
«modules»: [],
«allocator»: «tcmalloc»,
«environment»: «distmod»: «windows»,
«distarch»: «x86_64»,
«target_arch»: «x86_64»
>
>
Method # 3: Check the Mongodb Version with the File Path
The methods above are a way to obtain the mongodb version when the connection with the mongodb is not established. Here, we will fetch the version of our mongodb application by accomplishing the path of the file where the mongodb shell is located. To do this, we have launched the command prompt and with the “cd” command the full path of the mongodb shell is specified on the terminal. Then, press enter to execute the command.
The file path of mongodb is given and the system successfully finds the specified path of the mongodb. After that, we have given the name of the application “mongod.exe” which also utilizes the “–version” option for getting the mongodb version.
From the access of the file path of the mongodb, we have fetched the current mongodb version in the output represented below.
db version v6.0.3
Build Info: «version»: «6.0.3»,
«gitVersion»: «f803681c3ae19817d31958965850193de067c516»,
«modules»: [],
«allocator»: «tcmalloc»,
«environment»: «distmod»: «windows»,
«distarch»: «x86_64»,
«target_arch»: «x86_64»
>
>
Method # 4: Check the Mongodb Version with the db.version() Command
All the aforementioned commands use the command prompt for getting the mongodb version. We also have another method for figuring out the mongodb version: by launching the mongodb shell. In this instance, we first made the connection. Then, run the following query in the mongodb shell. The “db” keyword is used with the “version()” method for generating the version of the mongodb used in the system.
>db.version()
[/c]
The query for checking the mongodb version displayed the numerical output which is the mongodb version downloaded from our system.
[cc lang=»text» width=»100%» height=»100%» escaped=»true» theme=»blackboard» nowrap=»0″]
‘6.0.3’
Method # 5: Check the Mongodb Version with the BuildInfo Parameter Command
The last command line interface approach to get the mongodb version is using the “builInfo” method. A buildInfo command is a management tool that provides a build report for the current Mongod. We have employed the “runCommand()” query which takes the “buildInfo” command as a parameter. The buildInfo command is further set with the value “1” known as the true boolean value.
The output of the buildInfo command generates the version and the summary of the mongodb server.
version: ‘6.0.3’,
gitVersion: ‘f803681c3ae19817d31958965850193de067c516’,
targetMinOS: ‘Windows 7/Windows Server 2008 R2’,
modules: [],
allocator: ‘tcmalloc’,
javascriptEngine: ‘mozjs’,
sysInfo: ‘deprecated’,
versionArray: [ 6, 0, 3, 0 ],
openssl:
Method # 6: Check the Mongodb Version with the GUI Interface
The graphical user interface is the most appealing approach to checking the version of the mongodb. If the command line interface or any specific mongodb shell is not easy to use, then we can use the mongodb compass. The mongodb compass application is a GUI approach to getting the mongodb version. Firstly, we have launched the mongodb compass and built a connection with our existing local host. After that, we have three aligned dots on the left sidebar which on click displayed a few options. Among all the listed options, mouse over to the option “Connection info”. The screenshot of the mongodb compass is shown below which will be easy to follow the step for checking the mongodb version.
The “Connection info” generates the pop-up page where the information about the mongodb connection is given. On the pop-up page, we have a field “Edition”. Below the “Edition” field, the edition information of the mongodb is displayed as “MongoDB 6.0.3 Community”
Conclusion
The article is to check the version of mongodb. We have explored all the possible ways to get the mongodb version. A few methods are used to get the mongodb server version and other methods are for fetching the mongodb shell version. We first used the command line interface to check the mongodb version. Afterward, we have a mongodb compass GUI application were checking the mongodb version is easiest.
About the author
Saeed Raza
Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.
Check MongoDB Version
There are many places where you can get the version of MongoDB Server running.
MongoDB Version when MongoDB Server is started
When you start MongoDB Server, the version of MongoDB is echoed to the screen as db version v4.0.3 .
C:\>"C:\Program Files\MongoDB\Server\4.0\bin\mongod.exe" 2018-10-10T11:02:43.496+0530 I CONTROL [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none' 2018-10-10T11:02:43.799+0530 I CONTROL [initandlisten] MongoDB starting : pid=11716 port=27017 dbpath=C:\data\db\ 64-bit host=DESKTOP-QRVE3I1 2018-10-10T11:02:43.800+0530 I CONTROL [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2 2018-10-10T11:02:43.801+0530 I CONTROL [initandlisten] db version v4.0.3 2018-10-10T11:02:43.804+0530 I CONTROL [initandlisten] git version: 7ea530946fa7880364d88c8d8b6026bbc9ffa48c 2018-10-10T11:02:43.804+0530 I CONTROL [initandlisten] allocator: tcmalloc
In Ubuntu, run the following command to start Mongo Daemon.
sudo service mongod start
MongoDB version when Mongo Shell is started
When you start a Mongo Shell, versions of MongoDB Server and Mongo Shell are echoed to the screen.
C:\>"C:\Program Files\MongoDB\Server\4.0\bin\mongo.exe" MongoDB shell version v4.0.3 connecting to: mongodb://127.0.0.1:27017 Implicit session: session < "id" : UUID("fde958c1-c5e8-444b-87df-eec09d18cec4") >MongoDB server version: 4.0.3
Using db.version() command
To know the MongoDB version, you can also run db.version() command in Mongo Shell.
Conclusion
In this MongoDB Tutorial, we have learned how to check MongoDB Version through different ways like while starting MongoDB Server, Starting Mongo Shell and through db.version() command.