02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Inserting Collections and Documents in MongoDB

Inserting Collections and Documents in MongoDB

In this tutorial, we will be diving into creating collections and inserting documents in MongoDB, building on the concepts we learned in the previous lecture. MongoDB uses three primary components to organize data: databases, collections, and documents. Let’s break each of these down and learn how to use them effectively.

Understanding Databases, Collections, and Documents

  • Database: A MongoDB database is equivalent to a project. It is a container for collections, which hold documents. In this tutorial, we are working with a database called MongoSample, which we created in the previous lecture. This database will hold all the collections we need for our application.

  • Collection: A collection is the equivalent of a table in a traditional SQL database. However, unlike tables, collections do not require predefined schemas. Collections hold documents that are organized in a flexible, dynamic manner. In MongoDB, collections are created when documents are inserted into them.

  • Document: A document is a record in MongoDB that contains data in the form of key-value pairs. It is stored in collections and is similar to a row in an SQL table. Unlike traditional databases, each document can have a different structure, allowing for great flexibility.

In this tutorial, we will create our first collection and insert documents into it.

Step 1: Start MongoDB and Access the Mongo Shell

Before proceeding, ensure that your MongoDB server (using the mongod command) is running. Open a separate terminal window and start the Mongo shell by typing mongo.

Once in the Mongo shell, navigate to the MongoSample database that we created earlier by typing:

use MongoSample

This command switches you to the MongoSample database, allowing you to start working with it.

Step 2: Create a Collection

In MongoDB, collections do not require an explicit creation step. Instead, they are created dynamically the moment you insert your first document. To create a new collection called users, simply reference it in your code while inserting a document.

Here’s an example:

db.users.insert({ name: "Henry", age: 26, email: "henry@gmail.com" })

In this command:

  • db refers to the current database (MongoSample in our case).
  • users is the name of the collection, similar to a table in SQL.
  • .insert() is the method we use to add a new document into the users collection.

Since users didn’t exist before, MongoDB automatically creates it and inserts the document.

Step 3: Inserting Multiple Documents

We can also insert multiple documents by running the .insert() command again. Here is another example:

db.users.insert({ name: "Ben", age: 33, email: "ben@02geek.com" })

Unlike traditional databases where you have to define a table schema beforehand, MongoDB allows each document in a collection to have its own unique structure. Let’s insert another document, this time with additional attributes:

db.users.insert({ name: "Bell", age: 50, email: "bubbybell@gmail.com", children: ["Ben", "Sharon", "Laurie"] })

In this case, the document includes an additional field, children, which contains an array of names. This demonstrates MongoDB's flexibility, as each document can have different attributes without a predefined schema.

Benefits of MongoDB’s Flexibility

Traditional databases require all records in a table to adhere to a strict schema. For example, fields like name, email, and age must be predefined, and every record must conform to this format. This rigidity makes changing data structures cumbersome.

In MongoDB, documents are dynamic. You can add or remove fields at any time without worrying about schema constraints. This makes it easy to adapt to new requirements during the development process.

For instance, in our example, Bell’s document contains a children array, while Henry's and Ben's documents do not. This kind of flexibility is incredibly useful in modern web development, where requirements can change rapidly.

Summary

In this tutorial, you learned about MongoDB databases, collections, and documents. We practiced creating a collection by inserting documents directly into it, illustrating MongoDB's flexibility compared to traditional SQL databases. Each document can be unique, making MongoDB a great choice for dynamic, rapidly changing applications.

In the next lecture, we’ll cover how to query our database to retrieve specific documents, enabling us to interact with the data we've inserted.

Note: This video was created in 2016. MongoDB has evolved since then, with updated features and methods. For example, newer versions of MongoDB support insertOne() and insertMany() for more explicit document insertion, and the aggregation framework has been enhanced for more advanced data processing. Please refer to the official MongoDB documentation for the latest updates and features.

Video Transcript

00:01In the last lecture, we created our first database.
00:03And with that said, I want to take a freeze step here
00:06and focus on the three main terms
00:08that are available within MongoDB.
00:11Now, the first term, which we were just introduced
00:14to is a database.
00:15Now, databases in general are the
00:18project, the whole project.
00:19For example, if Zero to Geek has a database,
00:22it would have one database generally speaking,
00:24that would hold all the different information
00:26that we would want to relate to that website.
00:30A layer within it is basically a collection inside of it.
00:33And as that name applies, it is called a collection.
00:36Now, if you've ever worked with traditional
00:40SQL in traditional SQL world,
00:42you'd create a structure which is called a table.
00:45But because in no JS actually specifically in MongoDB
00:50and any no SQL technology, there are no tables,
00:54there's no pre-configured elements.
00:55Really what we're doing is we're creating a global
00:58object to that database.
01:00A global object to the database is called a collection.
01:04Alright? Now, once you've had a global object that's sitting
01:08inside of that database that is shared on the root
01:10of the database, then any content within it is
01:14considered a document.
01:16So that's it. Those are the three terms.
01:18With that said, let's jump right into this lecture
01:20as we're gonna learn how to create and insert content.
01:25Or more accurately, how do we create a document
01:27and insert it into a collection?
01:31Alrighty, so this is our last reminder.
01:33Make sure that your Mongo D database is actually running.
01:36It acts really as a database server
01:39in a separate turn terminal window.
01:41Just type Mongo.
01:42If you're not in that Mongo terminal already once in it,
01:46I want us to create again
01:48or go into our database that we've created,
01:50which we called Mongo Sample.
01:53Now that we're in using, we just define
01:56and set that we're using the Mongo sample database.
01:59I wanna show you what collections are.
02:01Collections if you ever worked
02:03with any database are very similar to tables only.
02:06They're dynamically created where you don't have
02:08to in advance decide what is the schema of your database.
02:13What you wanna do is you're gonna go to your db,
02:15which is the name that you always start with.
02:18And by the way, if you wanna know what's your version
02:20of your database, you could just type version
02:22and call a function
02:23and it's gonna return to you, your Mongo version.
02:25But you could see your O2 C
02:26that your MongoDB shell version is 3.26.
02:30So, but let's go back to our topic in hand.
02:32When I'm going to my db,
02:34I could actually create new collections literally
02:36by calling a collection name.
02:38For example, I want to create a new collection
02:41or is a similar name to it
02:43as a new table in the table terminology,
02:46although this really isn't a table, is to set the,
02:49the user table.
02:50This user collection, I'm not gonna call it table anymore,
02:52but it's comparable, although completely not the same
02:55because it's a collection, it's actually sort of an array.
02:59So into the, I'm creating it. That's how I created it.
03:02If it existed already,
03:03then it we're gonna basically talk to it.
03:05If it didn't exist yet, then we're creating it right now.
03:08So again, we call this the collection.
03:10So this is the, we're in the database of Mongo sample inside
03:13of the collection of users.
03:15Now let's go ahead and add our first user insert.
03:19And it's literally JavaScript.
03:20So what I'm gonna go ahead here,
03:22it's actually JSON, but it's JavaScript.
03:24Then the interpreter knows how
03:25to recognize when you're typing
03:27something that is not perfect.
03:28JSON. 'cause for example, in JSO, you need
03:30to type a name for example.
03:32But in JavaScript you could just type name
03:34and then the name of the user.
03:36So for example, the name of this user is Henry
03:39or Hen, well, let's just call him hen
03:42and their age is 27
03:45or well, 26 if I already typed it.
03:47Uh, what else do you wanna put here?
03:49Their name is that their age is that their email,
03:51let's say is hey gmail.com.
03:55This has is a string.
03:56So we wanna make sure that we quote it or double quote it.
04:00And that's it. We've created, we're creating now an insert.
04:03All we have to do now is type enter,
04:05and if we just inserted a new value, we inserted one item
04:09inside of the inside of the users.
04:11Now, by the way, I'm just gonna give you
04:13just the heads up on this.
04:14You could add one by one and for example, if I go ahead here
04:18and I'm just gonna, uh, click on the up arrow
04:20to get the same thing and let's go ahead
04:22and create another item.
04:23Let's create, uh, a new name, which will be called Ben.
04:26And his age is gonna be 33
04:28and his email is not gonna be Gmail, surprisingly,
04:31but it's gonna be ben@ohtwogeek.com,
04:35which actually zero two geek.com, which is my email.
04:38And you're more than welcome to email me if you have any
04:41questions or just wanna say hello.
04:42Okay, so I'm just gonna do that and I'm gonna click here.
04:45I'm gonna insert now what's so special about this system
04:47of adding things without creating originally a schema?
04:50'cause we didn't, A schema is basically a template.
04:53And let me show you an example of
04:55how traditional databases would create these things.
04:58So I'm gonna go ahead here.
04:59I'm just gonna open up Word and actually have Excel.
05:03And let me just open up here a new worksheet, new workbook.
05:07And imagine that this is a table
05:10now tables in which are very similar.
05:13It is incredibly similar to the way the
05:15traditional databases work.
05:16And in the traditional database, you would always have an ID
05:19or something comparable, which would be index.
05:21And then we would have a name,
05:23and then we would have maybe an email and then age
05:25and so on and so forth.
05:27They would be hard setted.
05:29And one of those values would be indexed.
05:31And when we say a value is indexed, it means
05:33that it has some sort of an index, some sort
05:35of a numbering system that is usually automatically assigned
05:38and added in as you add elements.
05:41The logic behind this of having this enclosed
05:44and defined logics that made a lot of sense
05:47for a very long time,
05:48but in this new age of development that we're in,
05:51when we want to have items
05:52and we wanna have elements dynamically created quickly
05:55without needing to go
05:56Through a process of changing a whole schema,
05:59changing a whole database, these easier structures
06:02of just adding inside information
06:04that are dynamically really creating these schemas are
06:07incredibly powerful.
06:08I wanna show you another something.
06:09For example, if I'm inserting here, another person,
06:11let's say I'm gonna add here.
06:13Um, bell and Bell's age is gonna be over 50, let's say.
06:18And her email is, I don't remember, I think it's Bubby Bell,
06:23Bubby bub.
06:25I'm not gonna give you her real email, right?
06:26We don't wanna bother her. So let's say it's blah@gmail.com,
06:30all that, all that's good,
06:31but how about this specific user has something
06:34special, something specific.
06:36And for example, um, this is oto, um, well,
06:40let's say has children.
06:41So, um, only whoever has children
06:46will have a, will have an array here.
06:48And the children's are gonna be, let's say Ben, um,
06:52let's say Ben and let's say Sharon
06:56and let's say Laurie.
07:00And now we've just inserted another item, another element.
07:03But this new element is kind
07:06of different than all the other elements
07:07that we've created previously.
07:09So what happened right now is previously
07:11we added only strings.
07:12Right now we're adding also arrays inside.
07:14We're adding more complex elements into our collection.
07:17If I would try to do this, for example, in
07:21a traditional database, suddenly I have your children.
07:25I don't have a physical way of adding more object inside.
07:29To be able to do that, I would have to create another table,
07:31and that table would have children
07:32and maybe I would have to sign IDs and so on and so forth.
07:35We'd have to create a structure
07:36that is a lot more com complex.
07:38So I'm not gonna compare more to tables.
07:40Their structures are a lot more complex than the structures
07:44when we're creating things than am.
07:45'cause all we're doing is inserting and adding things,
07:47and we could change things around whenever we want to.
07:50Alright, so that's really the basics of, oh,
07:53and I forgot to say, so we know what a database is.
07:55That is the Mongo sample, right?
07:57In this case, that's this current database
07:59that we're working with, that is its name.
08:01We saw what collections are.
08:02We created the user's collection
08:04that in many ways it's comparable to tables in traditional
08:08SQL type of, this is not SQL, this is no SQL.
08:11So these are literally objects.
08:13So every object that we add in is, is in the language
08:16of this database, is called a document.
08:18So we have documents that live in collections
08:21and collections live inside of a database.
08:24Okay? So that's it about how you create a database,
08:27how you create a collection,
08:29and how you add documents into those collections.
08:32In the next lecture, we want to continue
08:34'cause adding things in is good,
08:35but how about retrieving elements?
08:37How do we get those elements
08:38and how do we interact with them?
08:40And that's what we're gonna look at in the next lecture.
08:42In this lecture we got better familiarized with the terms
08:47database collection and document.
08:49We've also learned how
08:50to insert documents into a collection.
08:53In the next lecture, we're gonna take it, uh,
08:56to the other direction.
08:57Now that we have content within our database,
08:59how do we actually find documents inside
09:02of those collections?
09:03And that will be the topic of the next lecture.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!