Syntax highlighting of db/mongodb

= MongoDB =

<<TableOfContents(2)>>

== Полезные ссылки ==

[[https://www.mongodb.com/]]

== Сервер ==

[[https://www.mongodb.com/docs/manual/| Документация ]]


=== Установка сервера ===

 . [[https://www.mongodb.com/docs/manual/tutorial/install-mongodb-community-with-docker/#std-label-docker-mongodb-community-install|Install with Docker]]
 . [[https://www.mongodb.com/compatibility/docker|Docker and MongoDB]]

{{{#!highlight bash

docker volume create mongodata

docker run --name mongodb \
  -d \
  --restart=unless-stopped \
  -v mongodata:/data/db \
  -p 127.0.0.1:27017:27017 \
  -e MONGO_INITDB_ROOT_USERNAME=user \
  -e MONGO_INITDB_ROOT_PASSWORD=secret \
  mongodb/mongodb-community-server:latest
}}}

=== Установка и настройка клиeнта mongosh ===

[[https://www.mongodb.com/docs/mongodb-shell/install/#std-label-mdb-shell-install|Install mongosh]]

{{{#!highlight bash
wget -qO- https://www.mongodb.org/static/pgp/server-7.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-7.0.asc
sudo apt-get install gnupg
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
sudo apt-get update

sudo apt-get install -y mongodb-mongosh
mongosh --version
}}}

Подключение к БД

[[https://www.mongodb.com/docs/mongodb-shell/connect/|Connect to a Deployment]]

{{{#!highlight bash
mongosh "mongodb://localhost:27017"

# --- подключаемся с аутентификацией
mongosh "mongodb://localhost:27017" --username user --authenticationDatabase admin

# --- подключаемся с аутентификацией к БД my_database
mongosh "mongodb://localhost:27017/my_database" --username user --authenticationDatabase admin
}}}

=== Работаем в mongosh ===

Команды

{{{#!highlight bash
# --- переключение БД
use database
}}}

Агрегация

{{{#!highlight bash
# --- на входе - коллекция документов {filename: '/foo/bar'}
#      на выходе - один документ {filenames: ['/foo/bar1', '/foo/bar2', ...]}
db.parsedFiles.aggregate([ { $group: { _id: null, filenames: { $addToSet: "$filename" } } }, { $project: { _id: 0, filenames: 1 } }]);

# --- преобразование типов
#     на входе - {age: "25"}
#     на выходе - {age: 25}
db.students.aggregate([{$addFields: {age: {$toInt: "$age"}}}, {$out: "students"}])
}}}

=== Установка и настройка клиента Compass ===

 . [[https://www.mongodb.com/docs/compass/master/|What is MongoDB Compass]]
 . [[https://www.mongodb.com/try/download/compass|Download]]


{{{#!highlight bash
sudo dpkg -i mongodb-compass_1.39.0_amd64.deb
mongodb-compass
}}}