MongoDB stores data records as documents that are stored together in collections and the database stores one or more collections of documents.
Document: A document is a basic unit for storing data in the database. A single record of a collection is also known as a document. Basically, It is a structure that compromises key & value pairs which is similar to the JSON objects. Documents have a great ability to store complex data. For example:
Here, the name, country, age, and status are fields, and gfg, India, 21, and A are their values.
Collection: It is used to store a varied number of documents inside the database. As MongoDB is a Schema-free database, it can store documents that are not the same in structure. Also, there is no need to define the columns and their datatype.
Database: The MongoDB database is a container for collections and it can store one or more collections. It is not necessary to create a database before you work on it. The show dbs command gives the list of all the databases.
Creating a Database
In MongoDB, we can create a database using the use command. As shown in the below image
use gfgDB
Here, we have created a database named gfgDB. If the database doesnt exist, MongoDB will create the database when you store any data on it. Using this command we can also switch from one database to another.
How to view all the existing databases?
In MongoDB, we can view all the existing databases using the following command:
show dbs
This command returns a list of all the existing databases.
Creating a Collection
In MongoDB, a new collection is created when we add one or more documents to it. We can insert documents in the collection using the following methods:
- Inserting only one document in the collection
Here, we create a collection named myNewCollection1 by inserting a document that contains a name field with its value in it using insertOne() method.
- Inserting many documents into the collection
Here, we create a collection named myNewCollection2 by inserting two documents using insertMany()method.
How to view all the existing collections in the database?
In MongoDB, we can view all the existing collections in the database using the following command:
show collections
This command returns a list of all the existing collections in the gfgDB database.
Top comments (0)