Whatās MongoDB?
Ā
MongoDB is a non-relational document database that provides support for JSON-like storage. It is an open source NoSQL (Not only SQL) management program used as an alternative to traditional relational databases and can manage document-oriented information, store or retrieve information.
Ā
Hereās a MongoDB database structure :
Ā
Ā
Starter Guide
- To start working with MongoDB on your local Machine you will have to download a MongoDB Server.
- On the installation make sure to check the MongoDB Compass option, since it will be a great help to visualise and control your MongoDB collections, thereās also a helpful MongoDB Studio called Studio 3T, you can download it also to set up your development environment. but in this guide we will be using just MongoDB compass and the command line to understand the basics before moving any further.
- There you can create a new Connection, give it any name you want and specify the serverās URL : mongodb://localhost:27017/
the MongoDB server takes the port 27012 as you can see.
Ā
- then you can access your MongoDB databases, you will find 4 pre-created databases (admin, config, local and test) :
admin
,Ālocal
andconfig
Ā contain various settings local to the server, like users who are authenticated to connect. Under beginner usage, you shouldn't need to worry about them at all. By default you connect to a database namedĀtest
. To connect to a new database, justĀuse databasename
Ā from the mongo command line, orĀmongo databasename
Ā from your OS shell.
Ā
Now youāre all set to start working with MongoDB, letās get down to business!
letās take a quick round on the MongoDB compass, as you can see it visualizes our databases and collection(s) in a nice looking ways, like those cards below :
first thing first, open your integrated terminal and letās start checking things out, in the pre-created test database.
to switch the database you can use the following command (
use +
databaseName), like so : use test
this command actually has two uses, if the db already exists it will use it, but if the db doesn't exist yet, it will create it then use it.
Ā
Ā
š Creating Collections and Documents
to create a new collection in your database, you can simply use this command db.CollectionName.insert(), just like the
use
command, if the collection already exists, itās will append the new collection to it, and if it doesnāt, it will create a new collection with that name and insert those values in it.orrrrrr just create it simply using the following the createCollection() method.
TheĀ
db.createCollection()
Ā method has the following parameters :Ā
Parameter | Type | Description |
name | string | The name of the collection to create. SeeĀ Naming Restrictions. |
options | document | Optional. Configuration options for creating a:
⢠Capped collection
⢠Custered collection
⢠View |
you can give the insert() method either an array of objects or a single object, in this example letās try an array of objects and those are our Documents.
Ā
as you can see, i have a single collection in my database, and you may not have one.
letās make a new one together. letās call it
users
for example.db.users.insert([ { name : "oussama belhadi", email : "oussamabelhadi5@gmail.com" }, { name : "user 2", email : "user_email@gmail.com" } ])
Ā
if you get something like the response below, then your collection is created now, and if you noticed, it gives automatically each of our objects a unique id called
_id
, and itās our objectās id, it will be so useful later!Ā
Ā
Now just hit the refresh button and you will notice your new created collection, like so:
and just like that, ta da!
we have 2 documents inside our collection, and using compass you can visualize them on json, lists or table format.
Ā
Ā
Ā
ā Deleting Documents
To Delete a document we could use deleteOne() or the deleteMany() method and specify which document we want to delete the best way is using the _id field
exe :
db.users.deleteOne({_id:ObjectId("640d13179bcdc56b15f56e5f")})
That way only the one Object that has that Unique ID will be deleted, the other way is like so :
db.users.deleteMany({name : "user"})
all the objects that has "user" as a value to it's key name will be deleted.
Ā
š Updating Documents
To update a document we can use updateOne() or updateMany() with the updateMany() method, we could update so many documents that has a commune field at once.
the 2 methods accepts two object arguments the first one where we specify the id of our document and the second one has the $set operator
and a pair of key values of the elements we want to change.
ex :
db.books.updateOne( {_id:ObjectId("640d13179bcdc56b15f56e5f")}, {$set : {name : "zorous", email : "zorous@gmail.com"} } )
Ā
and to update many, instead of using the unique id, just use the commune field
db.books.updateMany( {name : "Oussama"}, {$set : {name : "Zorous"} } )
Ā
š„ The Most used methods
Fondamentales
The MongoDB methods can be used like a PIPLINE.
Whatās a pipeline?
InĀ software engineering aĀ pipeline consists of a chain of processing elements (processes ,Ā threads ,Ā coroutines ,Ā functions,Ā etc.), arranged so that the output of each element is the input of the next; just like the actual pipelines
the find() method
find() accepts two parameters the first is the condition inside an object, it can be empty like so
db.users.find()
just that means it will return every document.Ā
db.users.find()
Ā
as you can see it returns all the documents just like ā
SELECT * FROM table
ā in MySQL.Ā
The second parameter is optional itās an object that has the names of the fields you want to return as keys and either 0 or 1 as values.
1 means it will return that field, and 0 means it wonāt.
like on this example below, it will returns all the documents but on the 2nd parameter we setted the email as 1, so it will only return it
db.users.find({},{email:1})
Ā
but it also return the
_id
field by default.Now letās add a simple condition :
db.users.find({name : "oussama belhadi"})
as you can see, when you add a condition, the results change
it will return all the available objects inside the specified collection BUT with a condition like filtering, just like ā
SELECT * FROM users WHERE name = āoussama belhadi'
;" on MySQL.Ā
Ā
sort(), count() and limit()
- sort() : it accepts a parameter as an object and it's the field we want to sort with, if its value was 1 it will sort it ASC and if it was -1 it will be DESC.
this method should be used along with the find() method, otherways it will throw an error
db.users.find().sort({name : 1})
>> (it will return our documents sorted on ASC)
- count() : count only returns an integer, and itās the number of the fields
db.users.count() /*You can also use it like that on the pipline format, in case you want to add a filter to the results before actually counting */ db.users.find().count()
the both ways will return the
number of documents
in the users collection
>> 2
- limit(n) : it limits the number of the returned documents/objects to the specific number
db.users.limit(3)
>> (only 3 objects)
Operators on MongoDB
ALL THE OPERATORS IN MONGODB STARTS WITH THE DOLLAR SIGN "$"
Ā
__________ GREAT THAN / LESS THAN Operators _________
$gt : greater than and we use it like that :
db.CollectionName.find({rating : {$gt : 5}})
$lt : less than and we use it like that :
db.CollectionName.find({rating : {$lt : 10}})
Ā
$gte : greater than OR EQUALS and we use it like that :
db.CollectionName.find({rating : {$gte : 5}})
$lte : less than OR EQUALS and we use it like that :
db.CollectionName.find({rating : {$lte : 10}})
Ā
________OR and ALL Operators______
$or : it takes an array as a value and it will returns every satisfied condition, IT MUST BE USED AS THE FIRST ARGUMENT INSIDE FIND()
and we use it like that :
db.CollectionName.find( { $or : [{rating : 8} , {rating : 9} ] })
Ā
$all (AND) : it takes an array as a value also and it returns the objects where all the conditions are satisfied, and we use it like that :
db.CollectionName.find({category : {$all : ["Magic","Fantasy"] } })
Ā
____IN and NOT IN Operators____
the both takes an Array as a value and we use them like that :
db.CollectionName.find({rating : {$in : [7,8,9] } })
Hereās an example that explains their functionality, letās suppose we have a rating property in our object, and itās an integer between 1 and 10.
(it will return all the collections that has 7, 8 or 9 as a value)
Ā
while nin (NOTIN) is totally the opposite :
db.CollectionName.find({rating : {$nin : [7,8,9] } })
(it will return every single collection that doesnāt have 7,8 and 9 as a value to itās rate property.)
Ā
NESTED DOCUMENTS
Just like JSON we could use freely an array of objects inside our object, we call that Nested Documents here
ex :
{ "name" : "ex1", "nested docs" : [ {"title" : "a","review" : "xx"}, {"title" : "b","review" : "yy"}, {"title" : "c","review" : "zz"}, ] }
Ā
Conclusion
I believe thereās a lot more advanced queries, use cases and concepts on MongoDB.
Iāve covered just the basics in this post, thereās a lot more to learn!
Ā
In order to interact with the MongoDB databases from our Application we need to use Drivers for each programming language there's a specific driver which refers to a specific language bindings. thereās a lot of options but the most used ones i believe are either Node JS or Python.
Ā
Python Faker
In case you want to test MongoDBās Performance with huge amounts of data, which is a thing, MySQL canāt do, you can use Python to insert a huge amount of documents in a specific collection.
hereās the source code in case you want to check it out, it will keep on inserting random fake data in your collection as long as youāre running it, keep it running for an hour or so and you will find a millions of documents, then you can do your experiments, like checking how long it takes to fetch all of this data locally at least and you can compare it with MySQL.
just make sure to download the necessary packages (Faker, MongoClient) before you run it. and ofcourse you can change the arguments following to your likings! š¤
Ā
Ā