Premiers pas avec MongoDB

Exécution d’un fichier JavaScript dans MongoDB

./mongo localhost:27017/mydb myjsfile.js

Explication: Cette opération exécute le script myjsfile.js dans un shell mongo qui se connecte à la base de données mydb sur l’instance mongod accessible via l’interface localhost sur le port 27017. localhost:27017 n’est pas obligatoire car il s’agit du port par défaut utilisé par mongodb.

De plus, vous pouvez exécuter un fichier .js depuis la console mongo.

>load("myjsfile.js")

Rendre la sortie de find lisible dans le shell

Nous ajoutons trois enregistrements à notre test de collecte comme suit :

> db.test.insert({"key":"value1","key2":"Val2","key3":"val3"})
WriteResult({ "nInserted" : 1 })
> db.test.insert({"key":"value2","key2":"Val21","key3":"val31"})
WriteResult({ "nInserted" : 1 })
> db.test.insert({"key":"value3","key2":"Val22","key3":"val33"})
WriteResult({ "nInserted" : 1 })

Si nous les voyons via find, ils auront l’air très laids.

> db.test.find()
{ "_id" : ObjectId("5790c5cecae25b3d38c3c7ae"), "key" : "value1", "key2" : "Val2
", "key3" : "val3" }
{ "_id" : ObjectId("5790c5d9cae25b3d38c3c7af"), "key" : "value2", "key2" : "Val2
1", "key3" : "val31" }
{ "_id" : ObjectId("5790c5e9cae25b3d38c3c7b0"), "key" : "value3", "key2" : "Val2
2", "key3" : "val33" }

Pour contourner ce problème et les rendre lisibles, utilisez la fonction pretty().

> db.test.find().pretty()
{
        "_id" : ObjectId("5790c5cecae25b3d38c3c7ae"),
        "key" : "value1",
        "key2" : "Val2",
        "key3" : "val3"
}
{
        "_id" : ObjectId("5790c5d9cae25b3d38c3c7af"),
        "key" : "value2",
        "key2" : "Val21",
        "key3" : "val31"
}
{
        "_id" : ObjectId("5790c5e9cae25b3d38c3c7b0"),
        "key" : "value3",
        "key2" : "Val22",
        "key3" : "val33"
}
>

Termes complémentaires

Termes SQL Termes MongoDB
Base de données Base de données
Tableau Collecte
Entité / Ligne Documenter
Colonne Clé / Champ
Joindre une table [Documents intégrés][1]
Clé primaire [Clé primaire][2] (Clé par défaut _id fournie par mongodb lui-même)

[1] : https://docs.mongodb.com/manual/tutorial/model-embedded-one-to-many-relationships-between-documents/ [2] : https://docs.mongodb.com/manual/indexes/#default-id-index

Installation

Pour installer MongoDB, suivez les étapes ci-dessous :

  • Pour Mac OS :

    • There are two options for Mac OS: manual install or [homebrew][1].
    • Installing with [homebrew][1]:
      • Type the following command into the terminal:
        $ brew install mongodb
        
    • Installing manually:
      • Download the latest release [ici][2]. Assurez-vous que vous êtes téléchargement du fichier approprié, vérifiez spécialement si votre le type de système d’exploitation est 32 bits ou 64 bits. Le fichier téléchargé est au format tgz.

      • Go to the directory where this file is downloaded. Then type the following command:

        $ tar xvf mongodb-osx-xyz.tgz
        

        Instead of xyz, there would be some version and system type information. The extracted folder would be same name as the tgz file. Inside the folder, their would be a subfolder named bin which would contain several binary file along with mongod and mongo.

      • By default server keeps data in folder /data/db. So, we have to create that directory and then run the server having the following commands:

        $ sudo bash
        # mkdir -p /data/db
        # chmod 777 /data
        # chmod 777 /data/db
        # exit
        
      • To start the server, the following command should be given from the current location:

        $ ./mongod
        

        It would start the server on port 27017 by default.

      • To start the client, a new terminal should be opened having the same directory as before. Then the following command would start the client and connect to the server.

        $ ./mongo
        

        By default it connects to the test database. If you see the line like connecting to: test. Then you have successfully installed MongoDB. Congrats! Now, you can test [Hello World][3] to be more confident.

  • Pour les fenêtres:

    • Download the latest release [ici][2]. Assurez-vous que vous êtes téléchargement du fichier approprié, vérifiez spécialement si votre le type de système d’exploitation est 32 bits ou 64 bits.

    • The downloaded binary file has extension exe. Run it. It will prompt an installation wizard.

    • Click Next.

    • Accept the licence agreement and click Next.

    • Select Complete Installation.

    • Click on Install. It might prompt a window for asking administrator’s permission. Click Yes.

    • After installation click on Finish.

    • Now, the mongodb is installed on the path C:/Program Files/MongoDB/Server/3.2/bin. Instead of version 3.2, there could be some other version for your case. The path name would be changed accordingly.

    • bin directory contain several binary file along with mongod and mongo. To run it from other folder, you could add the path in system path. To do it:

      • Right click on My Computer and select Properties.
      • Click on Advanced system setting on the left pane.
      • Click on Environment Variables… under the Advanced tab.
      • Select Path from System variables section and click on Edit….
      • Before Windows 10, append a semi-colon and paste the path given above. From Windows 10, there is a New button to add new path.
      • Click OKs to save changes.
    • Now, create a folder named data having a sub-folder named db where you want to run the server.

    • Start command prompt from their. Either changing the path in cmd or clicking on Open command window here which would be visible after right clicking on the empty space of the folder GUI pressing the Shift and Ctrl key together.

    • Write the command to start the server:

      > mongod
      

      It would start the server on port 27017 by default.

    • Open another command prompt and type the following to start client:

      > mongo
      
    • By default it connects to the test database. If you see the line like connecting to: test. Then you have successfully installed MongoDB. Congrats! Now, you can test [Hello World][4] to be more confident.

  • Pour Linux : Presque identique à Mac OS, sauf qu’une commande équivalente est nécessaire.

    • For Debian-based distros (using apt-get):
      • Import MongoDB Repository key.

        $ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
        gpg: Total number processed: 1\
        gpg:               imported: 1  (RSA: 1)
        
      • Add repository to package list on Ubuntu 16.04.

        $ echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
        
      • on Ubuntu 14.04.

        $ echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
        
      • Update package list.

        $ sudo apt-get update
        
      • Install MongoDB.

        $ sudo apt-get install mongodb-org
        
    • For Red Hat based distros (using yum):
      • use a text editor which you prefer.

        $ vi /etc/yum.repos.d/mongodb-org-3.4.repo

      • Paste following text.

        [mongodb-org-3.4]
        name=MongoDB Repository
        baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/
        gpgcheck=1
        enabled=1
        gpgkey=https://www.mongodb.org/static/pgp/server-3.4.asc
        
      • Update package list.

        $ sudo yum update
        
      • Install MongoDB

        $ sudo yum install mongodb-org
        

[1] : https://brew.sh/ [2] : https://www.mongodb.com/download-center#community [3] : https://www.wikiod.com/fr/mongodb/premiers-pas-avec-mongodb#Bonjour le monde [4] : https://www.wikiod.com/fr/mongodb/premiers-pas-avec-mongodb#Bonjour le monde

Commandes de base sur mongo shell

Afficher toutes les bases de données disponibles :

show dbs;

Sélectionnez une base de données particulière à laquelle accéder, par ex. madb. Cela créera mydb s’il n’existe pas déjà :

use mydb;

Afficher toutes les collections de la base de données (assurez-vous d’abord d’en sélectionner une, voir ci-dessus) :

show collections; 

Afficher toutes les fonctions pouvant être utilisées avec la base de données :

db.mydb.help();

Pour vérifier votre base de données actuellement sélectionnée, utilisez la commande db

> db
mydb

La commande db.dropDatabase() est utilisée pour supprimer une base de données existante.

db.dropDatabase()

Bonjour le monde

Après le processus d’installation, les lignes suivantes doivent être saisies dans mongo shell (terminal client).

> db.world.insert({ "speech" : "Hello World!" });
> cur = db.world.find();x=cur.next();print(x["speech"]);

Bonjour le monde !

Explication:

  • Dans la première ligne, nous avons inséré un document apparié { clé : valeur } ​​dans la base de données par défaut test et dans la collection nommée world.
  • Dans la deuxième ligne on récupère les données que l’on vient d’insérer. Les données récupérées sont conservées dans une variable javascript nommée cur. Ensuite, par la fonction next(), nous avons récupéré le premier et unique document et l’avons conservé dans une autre variable js nommée x. Puis imprimé la valeur du document fournissant la clé.