Livres Ebooks

MongoDB® Notes for Professionals – Télécharger Cours mongo db gratuitement

Chapter 1: Getting started with MongoDB

Section 1.1: Execution of a JavaScript file in MongoDB
./mongo localhost:27017/mydb myjsfile.js
Explanation: This operation executes the myjsfile.js script in a mongo shell that connects to the mydb database on
the mongod instance accessible via the localhost interface on port 27017. localhost:27017 is not mandatory as this
is the default port mongodb uses.
Also, you can run a .js file from within mongo console.
>load(« myjsfile.js »)
Section 1.2: Making the output of find readable in shell
We add three records to our collection test as:
> 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 })
If we see them via find, they will look very ugly.
> 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 » }
To work around this and make them readable, use the pretty() function.
> db.test.find().pretty() – MongoDB® Notes for Professionals 3
« _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 »
Section 1.3: Complementary Terms
SQL Terms MongoDB Terms
Database Database
Table Collection
Entity / Row Document
Column Key / Field
Table Join Embedded Documents
Primary Key Primary Key (Default key _id provided by mongodb itself)
Section 1.4: Installation
To install MongoDB, follow the steps below:
For Mac OS:
There are two options for Mac OS: manual install or homebrew.
Installing with homebrew:
Type the following command into the terminal:
$ brew install mongodb
Installing manually:
Download the latest release here. Make sure that you are downloading the appropriate file,
specially check whether your operating system type is 32-bit or 64-bit. The downloaded file is in
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 – MongoDB® Notes for Professionals 4

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 to be more
For Windows:
Download the latest release here. Make sure that you are downloading the appropriate file, specially
check whether your operating system type is 32-bit or 64-bit.
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
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 – MongoDB® Notes for Professionals 5

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 to be more confident.
For Linux: Almost same as Mac OS except some equivalent command is needed.
For Debian-based distros (using apt-get):
Import MongoDB Repository key.
$ sudo apt-key adv –keyserver hkp:// –recv EA312927
gpg: Total number processed: 1\
gpg: imported: 1 (RSA: 1)
Add repository to package list on Ubuntu 16.04.
$ echo « deb xenial/mongodb-org/3.2 multiverse »
| sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
on Ubuntu 14.04.
$ echo « deb 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.
name=MongoDB Repository
Update package list.
$ sudo yum update
Install MongoDB
$ sudo yum install mongodb-org – MongoDB® Notes for Professionals 6
Section 1.5: Basic commands on mongo shell
Show all available databases:
show dbs;
Select a particular database to access, e.g. mydb. This will create mydb if it does not already exist:
use mydb;
Show all collections in the database (be sure to select one first, see above):
show collections;
Show all functions that can be used with the database:;
To check your currently selected database, use the command db
> db
db.dropDatabase() command is used to drop a existing database.
Section 1.6: Hello World
After installation process, the following lines should be entered in mongo shell (client terminal).
>{ « speech » : « Hello World! » });
> cur =;;print(x[« speech »]);

Hello World!

In the first line, we have inserted a { key : value } paired document in the default database test and in
the collection named world.
In the second line we retrieve the data we have just inserted. The retrieved data is kept in a javascript
variable named cur. Then by the next() function, we retrieved the first and only document and kept it in
another js variable named x. Then printed the value of the document providing the key. – MongoDB® Notes for Professionals 7
Chapter 2: CRUD Operation
Section 2.1: Create
db.people.insert({name: ‘Tom’, age: 28});
Or{name: ‘Tom’, age: 28});
The difference with save is that if the passed document contains an _id field, if a document already exists with that
_id it will be updated instead of being added as new.
Two new methods to insert documents into a collection, in MongoDB 3.2.x:
Use insertOne to insert only one record:
db.people.insertOne({name: ‘Tom’, age: 28});
Use insertMany to insert multiple records:
db.people.insertMany([{name: ‘Tom’, age: 28},{name: ‘John’, age: 25}, {name: ‘Kathy’, age: 23}])
Note that insert is highlighted as deprecated in every official language driver since version 3.0. The full distinction
being that the shell methods actually lagged behind the other drivers in implementing the method. The same thing
applies for all other CRUD methods
Section 2.2: Update
Update the entire object:
db.people.update({name: ‘Tom’}, {age: 29, name: ‘Tom’})
// New in MongoDB 3.2
db.people.updateOne({name: ‘Tom’},{age: 29, name: ‘Tom’}) //Will replace only first matching
db.people.updateMany({name: ‘Tom’},{age: 29, name: ‘Tom’}) //Will replace all matching documents.
Or just update a single field of a document. In this case age:
db.people.update({name: ‘Tom’}, {$set: {age: 29}})
You can also update multiple documents simultaneously by adding a third parameter. This query will update all
documents where the name equals Tom:
db.people.update({name: ‘Tom’}, {$set: {age: 29}}, {multi: true})
// New in MongoDB 3.2
db.people.updateOne({name: ‘Tom’},{$set:{age: 30}) //Will update only first matching document.
db.people.updateMany({name: ‘Tom’},{$set:{age: 30}}) //Will update all matching documents.
If a new field is coming for update, that field will be added to the document. – MongoDB® Notes for Professionals 8
db.people.updateMany({name: ‘Tom’},{$set:{age: 30, salary:50000}})// Document will have `salary`
field as well.
If a document is needed to be replaced,
db.collection.replaceOne({name:’Tom’}, {name:’Lakmal’,age:25,address:’Sri Lanka’})
can be used.
Note: Fields you use to identify the object will be saved in the updated document. Field that are not defined in the
update section will be removed from the document.
Section 2.3: Delete
Deletes all documents matching the query parameter:
// New in MongoDB 3.2
db.people.deleteMany({name: ‘Tom’})
// All versions
db.people.remove({name: ‘Tom’})
Or just one
// New in MongoDB 3.2
db.people.deleteOne({name: ‘Tom’})
// All versions
db.people.remove({name: ‘Tom’}, true)
MongoDB’s remove() method. If you execute this command without any argument or without empty argument it
will remove all documents from the collection.
Section 2.4: Read
Query for all the docs in the people collection that have a name field with a value of ‘Tom’:
db.people.find({name: ‘Tom’})
Or just the first one:
db.people.findOne({name: ‘Tom’})
You can also specify which fields to return by passing a field selection parameter. The following will exclude the _id
field and only include the age field:
db.people.find({name: ‘Tom’}, {_id: 0, age: 1}) – MongoDB® Notes for Professionals 9
Note: by default, the _id field will be returned, even if you don’t ask for it. If you would like not to get the _id back,
you can just follow the previous example and ask for the _id to be excluded by specifying _id: 0 (or _id: false).If
you want to find sub record like address object contains country, city, etc.
db.people.find({‘’: ‘US’})
& specify field too if required
db.people.find({‘’: ‘US’}, {‘name’: true, ‘’: true})Remember that the
result has a `.pretty()` method that pretty-prints resulting JSON:
Section 2.5: Update of embedded documents
For the following schema:
{name: ‘Tom’, age: 28, marks: [50, 60, 70]}
Update Tom’s marks to 55 where marks are 50 (Use the positional operator $):
db.people.update({name: « Tom », marks: 50}, {« $set »: {« marks.$ »: 55}})
For the following schema:
{name: ‘Tom’, age: 28, marks: [{subject: « English », marks: 90},{subject: « Maths », marks: 100},
{subject: « Computes », marks: 20}]}
Update Tom’s English marks to 85 :
db.people.update({name: « Tom », « marks.subject »: « English »},{« $set »:{« marks.$.marks »: 85}})
Explaining above example:
By using {name: « Tom », « marks.subject »: « English »} you will get the position of the object in the marks array, where
subject is English. In « marks.$.marks », $ is used to update in that position of the marks array
Update Values in an Array
The positional $ operator identifies an element in an array to update without explicitly specifying the position of the
element in the array.
Consider a collection students with the following documents:
{ « _id » : 1, « grades » : [ 80, 85, 90 ] }
{ « _id » : 2, « grades » : [ 88, 90, 92 ] }
{ « _id » : 3, « grades » : [ 85, 100, 90 ] }
To update 80 to 82 in the grades array in the first document, use the positional $ operator if you do not know the
position of the element in the array:
{ _id: 1, grades: 80 },
{ $set: { « grades.$ » : 82 } } – MongoDB® Notes for Professionals 10
Section 2.6: More update operators
You can use other operators besides $set when updating a document. The $push operator allows you to push a
value into an array, in this case we will add a new nickname to the nicknames array.
db.people.update({name: ‘Tom’}, {$push: {nicknames: ‘Tommy’}})
// This adds the string ‘Tommy’ into the nicknames array in Tom’s document.
The $pull operator is the opposite of $push, you can pull specific items from arrays.
db.people.update({name: ‘Tom’}, {$pull: {nicknames: ‘Tommy’}})
// This removes the string ‘Tommy’ from the nicknames array in Tom’s document.
The $pop operator allows you to remove the first or the last value from an array. Let’s say Tom’s document has a
property called siblings that has the value [‘Marie’, ‘Bob’, ‘Kevin’, ‘Alex’].
db.people.update({name: ‘Tom’}, {$pop: {siblings: -1}})
// This will remove the first value from the siblings array, which is ‘Marie’ in this case.
db.people.update({name: ‘Tom’}, {$pop: {siblings: 1}})
// This will remove the last value from the siblings array, which is ‘Alex’ in this case.
Section 2.7: « multi » Parameter while updating multiple
To update multiple documents in a collection, set the multi option to true.
upsert: boolean,
multi: boolean,
writeConcern: document
multi is optional. If set to true, updates multiple documents that meet the query criteria. If set to false, updates one
document. The default value is false.
db.mycol.find() { « _id » : ObjectId(598354878df45ec5), « title »: »MongoDB Overview »} { « _id » :
ObjectId(59835487adf45ec6), « title »: »NoSQL Overview »} { « _id » : ObjectId(59835487adf45ec7),
« title »: »Tutorials Point Overview »}

db.mycol.update({‘title’:’MongoDB Overview’}, {$set:{‘title’:’New MongoDB Tutorial’}},{multi:true}) – MongoDB® Notes for Professionals 11
Chapter 3: Getting database information
Section 3.1: List all collections in database
show collections
show tables
Section 3.2: List all databases
show dbs

Télécharger gratuitement 

Articles similaires

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.

Bouton retour en haut de la page

Adblock détecté

S'il vous plaît envisager de nous soutenir en désactivant votre bloqueur de publicité