MongoDB for NoSQL

MongoDB for NoSQL

MongoDB is open-source and one of the leaders in the document-oriented NoSQL database segment, one of four categories of NSQL databases.

A document-oriented NoSQL database replaces the concept of "row" as in relational databases with a more flexible model, the "document." It is crucial to make this parallel and understand that another category is another strategy and another thought in terms of data storage - you need to be open-minded to receive a new way of storing data.

Main features of MongoDB

- Indexing

MongoDB supports secondary indexes, allowing faster queries to build.

- Aggregation

MongoDB enables the construction of complex aggregations of data, optimizing performance.

- Special Data Type

Data types are one of the peculiarities of NoSQL banks. Because it was modeled for Big Data, they have their data types of working with data generated at high volume, high variability, and high speed. Therefore, MongoDB supports time-to-live collections for data that expires at a particular time, such as sessions.?

- Storage

MongoDB supports the storage of large amounts of data. Some characteristics present in relational databases are not present in MongoDB, including some types of joins and multiline transactions.

MongoDB x RDBMS

A comparison between MongoDB which is of the NoSQL category, and some database any of the RDBMS category:

N?o foi fornecido texto alternativo para esta imagem

Where to use MongoDB?

We can use MongoDB for Big Data, content management, Social and Mobile infrastructure, user data management, and Enterprise Data Hub. We have a Data Warehouse, Data Lake, NoSQL Databases, and various storage structures within an infrastructure according to the significant data project needs.

You can no longer think of a single data storage structure. Today we live in a new world, and we need to adapt to new technologies.

In this tutorial, we will see the creation of the first collection of data, but mainly understand how we can use the tool to use it and what advantages it brings to our daily life.

We'll see how to manipulate data with insertion, alteration, update, or removal completely and by parts. We'll also cover how MongoDB operators apply in several of these phases of data search and change with a series of rule and operator invocations that we use to that data.

Proximity search

In addition, we will see one of the common uses of MongoDB, which is the proximity search. For example, we have several students from a college, and for a particular student, we want to know the people closest to him to do a group job.

The proximity search is widespread, especially when we seek a market, restaurant, or company near where we are. Things close to other things.

Creating collections and records

Let's create collections within our MongoDB, work with MongoDB as if it were a bunch of data.

We will create a collection of students in MongoDB, but in it, we do not work with tables with fixed structures. Instead, we indicate to the database to create a collection called "students" regardless of the format it is:

db.createCollection("students")        
N?o foi fornecido texto alternativo para esta imagem

Therefore, we have a collection of students already created. Now let's insert a student into the student's collection, that is, a JavaScript object, by primarily remembering json's notation:

{ 
  "name" : "Leo Anello",
  "date_of_birth" : "19920131"
}        

Note that we had to indicate the name field and the date of birth field. After all, at no point did we talk about the student's collection and its structure. If we want to insert something from the structure, we need to indicate each element, document, or thing we are inserting.

If this is a JavaScript object, we can create objects with keys and value. For example, in MongoDB JavaScript, we have the data object:

db.students.insert(
{ 
  "name" : "Leo Anello",
  "date_of_birth" : new Date(1992,01,31)
})        

Now let's insert the student into MongoDB:

N?o foi fornecido texto alternativo para esta imagem

The same way we enter a student, let's enter more information. In our case, we want to insert the course that the student is enrolled in the MBA.

What's the name of the course?

Since we're working with JavaScript objects, we can have a description of a course in the object:

db.students.insert(
{ 
  "name" : "Leo Anello",
  "date_of_birth" : new Date(1992,01,31),
  "MBA" : {
     "name": "Big Data & Data Science"
      }
})        

We can go further. We can enter what the grades that the student has already had are:

db.students.insert(
{ 
  "name" : "Leo Anello",
  "date_of_birth" : new Date(1992,01,31),
  "MBA" : {
     "name": "Big Data & Data Science"},
  "grades" : [10.0, 9.0, 9.0]
})        

Let's add extra student information, let's pass it inside an array in skills:

db.students.insert(
  { 
  "name" : "Leo Anello",
  "date_of_birth" : new Date(1992,01,31),
  "MBA" : {
   "name" : "Big Data & Data Science"},
  "grades" : [10.0, 9.0, 9.0],
  
  "skills" : [
    {"name" : "english",
     "level" : "advanced"},
    {"name" : "swimming", 
     "level" : "basic"} ]
   })        

We describe the name of the skill and the level of the ability:

N?o foi fornecido texto alternativo para esta imagem

We were able to insert an object/document representing the student, course, course, skills he has, date of birth, and grades. All this at once. In a single insert, we were able to enter all these values.

Check and search

In MongoDB, if we want to check the inserted students, we can talk to the database to pick them up with the find() command:

db.students.find()        

Let's insert more elements into the document, remove repeated values, do searches, and compare how we would do it in a traditional relational database.

Remove duplicate records

If we want to insert more people so that we have a bank with more values and remove who is duplicated, in case we delete a record with a specific ID:

db.students.remove({
 "_id" : ObjectId("88cb0008cdfv88gh88gf88cx8c")
})        

Therefore, when we indicate removes, we pass an object in braces to precisely describe the search that should be made and eliminate it - in this case, we look for id.

To check the remaining records, repeat the command:

db.students.find()        

If we want to include more people in the set:

db.students.insert(
{
    "name" : "Koki",
    "date_of_birth" : "1998, 08, 30", 
    "mba" : {
        "name": "automation", 
    },
    "skills": [
      {
        "name"  : "english", 
        "level" : "advanced"
      }
    ]
})
db.students.insert(
{
    "name" : "Pellegrini",
    "date_of_birth" : "1990, 08, 30", 
    "mba" : {
        "name": "international_relations", 
    },
    "skills": [
      {
        "name"  : "english", 
        "level" : "fluent"
      }
    ]
})
db.students.insert(
{
    "name" : "Enock",
    "date_of_birth" : "1974, 10, 10", 
    "mba" : {
        "name": "IT", 
    },
    "skills": [
      {
        "name"  : "english", 
        "level" : "fluent"
      }
    ]
})        

Quotation marks on the keys are optional. However, we use some cases because we may have some invalid character, but we would like to use as keys. Therefore, we can follow the waterings of JavaScript objects as good practices.

How to do all this in a relational database?

In the relational bank, we must define in advance the whole structure. However, this does not mean that in all relational databases, we should do this. Each extension allows us to do different things.

Now that we've put much data about multiple students within our student collection let's see what it would look like in a relational database.

CREATE TABLE mba (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255));        

The courses have an ID and name. Now we create the student table:

CREATE TABLE students (
id INTEGER PRIMARY KEY AUTO_INCREMENT, 
name VARCHAR(255), 
mba_id INTEGER,
date_of_birth DATE));        

Grade table:

CREATE TABLE grades (
id INTEGER PRIMARY KEY AUTO_INCREMENT, 
grade DECIMAL (3,2), 
student_id INTEGER);        

Skill table:

CREATE TABLE skills (
id INTEGER PRIMARY KEY AUTO_INCREMENT, 
name VARCHAR(255),
level VARCHAR(255), 
student_id INTEGER);        

In relational databases, we need 4 CREATE TABLE commands to create our collections. In MongoDB, we can create a complete assembly with a single order, simply indicating:

db.createCollection("students")        

However, relational databases support guarantees that MongoDB or semi-structured data cannot endorse specific rules - it is a decision to make. In contrast, DB brings advantages of having the freedom of structure, which a traditional database by default does not have.?

In some situations, we will want a more flexible structure, and in others, we will need more fixed structures. The decision is not for the minimum of words; the decision is according to what the tool offers - we were able to create the structure of students who may or may not contain some fields that others will not have.

Advantage and Disadvantage?

  • MongoDB is widely used when we need to perform proximity searches, such as locating the pizzeria closest to you.
  • In situations where MongoDB is not indicated, we need to do many aggregation operations in a single query; this has many costs for MongoDB.

Querying and Filtering Data

We already had a collection of students. It is composed of several elements, and we can observe this by typing db.students.find(). Thus, everything that follows an empty pattern is shown. We'll see all the objects, only in a very illegible way.

N?o foi fornecido texto alternativo para esta imagem

To be able to read more clearly, we can type db.students.find().pretty() and will be shown the objects in a more readable way:

N?o foi fornecido texto alternativo para esta imagem

Now, we'll learn what kinds of things work at MongoDB. First, we'll look at the find as an unfiltered select from a non-relational database. Sometimes, however, we don't want to find everything but a specific pattern. For this, we use the db.students.find(), and in the parentheses, we pass the reference of what we want.?

If we had more than one object named "Leo Anello," he would bring all the students called "Leo Anello". Find works, by default, going through all the objects and looking in them for the field we are looking for. All those who have the same reference are separated and are shown, that is, returned to us. Find does a search that, by default, is quite simple. It scans all documents and searches for all elements that have the same characteristics passed, for example, a "name."

Let's now see some equivalences. When we type:

db.students.find({ nome : "Leo Anello"})        

This is equivalent to saying, in SQL:

SELECT * FROM students WHERE name = "Leo Anello"        

We can search students using references other than just their "names," for example, for skills. In this case, we will seek the "English" skill. Thus, we will look for students whose skills have the name "English." We'll type in the Editor first and paste it into the Terminal. We will use find, pretty, and specify the English ability to do this search. Note:

db.students.find({ "skills.name" : "english" }).pretty()        

We will have the following answer:

N?o foi fornecido texto alternativo para esta imagem

We have three students whose skills are English.

It is simple to perform a search on an inner element of the tree and document. We entered these elements through the find and the reference we passed, the "skills.name". We can even search for the skill by a specific "name," for example, the students called "Pellegrini" who make English. To do this, we can write the following:

db.students.find({
"name" : "Pellegrini", 
"skills.name" : "english"})        
N?o foi fornecido texto alternativo para esta imagem



We were able to search using a different document field, simply passing an example, a value, of what we are looking for.

Remembering that we're not in a typing competition. It's not because we type less using?DB.students.find?that it's better. In both cases, we have advantages and also disadvantages. The?DB.students.find?query is simple to bring equalities; it brings the entire document by default, even if we want a little piece. SELECT* would get only a tiny part, even if we wanted to be whole. It is important to remember; however, both do the same things. It all depends on what we need and how we use it. But notice that it's easier to query?DB.students.find?than SQL because it looks more complex.

The goal was also to show the find. Let's work on some types of queries in MongoDB, and we'll learn various uses of find. If we go into the MongoDB Collection find documentation, we will see that the number of things we can do is vast.

Find with or and in

Imagine that we want to seek students enrolled in technology courses, such as "Information System" and "Chemical Engineering." We could do a different query for each of these MBA courses.

However, this ends up being somewhat limited. In practice, we want to run a query with the condition that is either a value or the other value. If we tried in a query to put the options "automation", "international_relations," and "IT" we would have the following:

db.students.find({
    "mba.name" : "automation",
    "mba.name" : "international_relations",
    "mba.name" : "IT"
   })        
N?o foi fornecido texto alternativo para esta imagem

Note, we are shown only the student who attends "automation" and "international_relations"; however, the first information we pass is ignored.

We're using javascript, so we're sensitive to its rules. The javascript dictionary is a set of keys and values. The key is unique, and it has only one value at a time. When we put in a key two names, the second subscribes to the first; that is, it is as if we had not written the first. So we have to do another procedure; we can isolate the objects and put them in different dictionaries. Note:

"mba.name" : "automation",
"mba.name" : "international_relations",
"mba.name" : "IT"        

When we have multiple objects and want to group them, we can use a javascript array. First, we have to say that we would like any of the queries that are inside the Array. For this, we use the or to communicate, "or" one thing "or" the other:

db.students.find({
    $or : [
        {"mba.name" : "automation"},
        {"mba.name" : "international_relations"},   
        {"mba.name" : "IT"} 
    ]
})        
N?o foi fornecido texto alternativo para esta imagem

And now, if we wanted to look for only the "Pellegrini" students who are in these courses? We have two ways to try to change this code. We can enter a third condition with the name "Pellegrini" ({"name": Pellegrini}), just below the courses.

But that won't work because or makes any of the options true. So it doesn't make sense to put the name "Pellegrini" along with the names of the courses. We mean that we seek anyone in one of the two courses and whose student name is "Pellegrini." That is, on condition that it has the name "Pellegrini." This, therefore, is something external; we will not put inside the keys, but somewhat outside:

db.students.find({
    $or : [
        {"mba.name" : "Music"},
        {"mba.name" : "Business"}    
    ],
    "name" : "Pellegrini"
})        

If we paste this in the Terminal, we will see that it will be working, as we do not have "Pellegrini" attending Music or Business, it will not bring us anything. We can test by putting another course, that of "international relations":

db.students.find({
    $or : [
        {"mba.name" : "Music"},
        {"mba.name" : "Business"},
        {"mba.name" : "international_relations"}],
         "name" : "Pellegrini"
})        

And now, if we wanted to look for only the "Pellegrini" who are in these courses? We have two ways to try to change this code. We can enter a third condition with the name "Pellegrini" ({"name": "Pellegrini"}), just below the courses.

We have several other conditions, and this can be read in the MongoDB documentation, referring to the find method, which we can find in: MongoDB Documentation. If we want to know even more details about MongoDB, in this case, or play on google, seek the documentation and see what conditions should be passed when we use it.

In

in may be easier to use in some cases. If we have questions, we can search mongo's documentation on the in. As in SQL, we have a different way of using things. Let's see how we use it in DB. We mean that the "mba.name" will be "in" (within) of "IT," "Automation." We will write the following:

db.students.find({
    "mba.name" : {
        $in : ["automation", "IT"]
        }
})        
N?o foi fornecido texto alternativo para esta imagem

With this, we saw both the in and the or and showed how valid it is to seek information in the documentation and not be afraid to apply it to daily life.

And there we have it. I hope you have found this helpful. Thank you for reading. ??

要查看或添加评论,请登录

社区洞察

其他会员也浏览了