The Wayback Machine - https://web.archive.org/web/20241126183023/https://www.geeksforgeeks.org/mongodb-database-collection-and-document/
Open In App

MongoDB – Database, Collection, and Document

Last Updated : 01 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Databases, collections, documents are important parts of MongoDB without them you are not able to store data on the MongoDB server. A Database contains one or more collections, and a collection contains documents and the documents contain data, they are related to each other. 

Image

Database

In MongoDB, a database contains the collections of documents. One can create multiple databases on the MongoDB server.  

View Database:

To see how many databases are present in your MongoDB server, write the following statement in the mongo shell:  

show dbs

For Example:  

Image

Here, we freshly started MongoDB so we do not have a database except these three default databases, i.e, admin, config, and local.  

Naming Restriction for Database:

Before creating a database you should first learn about the naming restrictions for databases:  

  • In MongoDB, the names of the database are case insensitive, but you must always remember that the database names cannot differ only by the case of the characters.
  • For windows user, MongoDB database names cannot contain any of these following characters: 
/\. "$*:|?
  • For Unix and Linux users, MongoDB database names cannot contain any of these following characters: 
/\. "$
  • MongoDB database names cannot contain null characters(in windows, Unix, and Linux systems).
  • MongoDB database names cannot be empty and must contain less than 64 characters. 

Creating Database:

In the mongo shell, you can create a database with the help of the following command:  

use database_name 

This command actually switches you to the new database if the given name does not exist and if the given name exists, then it will switch you to the existing database. Now at this stage, if you use the show command to see the database list where you will find that your new database is not present in that database list because, in MongoDB, the database is actually created when you start entering data in that database. 

For Example:  

Image

Here, we create a new database named GeeksforGeeks using the use command. After creating a database when we check the database list we do not find our database on that list because we do not enter any data in the GeeksforGeeks database. 

Collection

Collections are just like tables in relational databases, they also store data, but in the form of documents. A single database is allowed to store multiple collections.  

Schemaless:

As we know that MongoDB databases are schemaless. So, it is not necessary in a collection that the schema of one document is similar to another document. Or in other words, a single collection contains different types of documents like as shown in the below example where mystudentData collection contain two different types of documents: 

Image

Naming Restrictions for Collection:

Before creating a collection you should first learn about the naming restrictions for collections: 

  • Collection name must starts with an underscore (`_`) or a letter (a-z or A-Z)
  • Collection name should not start with a number, and does not contain $, empty string, null character and does not begin with prefix `system.` as this is reserved for MongoDB system collections.
  • The maximum length of the collection name is 120 bytes(including the database name, dot separator, and the collection name).

Creating collection:

After creating database now we create a collection to store documents. The collection is created using the following syntax: 

db.collection_name.insertOne({..})

Here, insertOne() function is used to store single data in the specified collection. And in the curly braces {} we store our data or in other words, it is a document. 

For Example:  

Image

In this example, we create a collection named as the Author and we insert data in it with the help of insertOne() function. Or in other words, {name: “Ankita”} is a document in the Author collection, and in this document, the name is the key or field and “Ankita” is the value of this key or field. After pressing enter we got a message(as shown in the above image) and this message tells us that the data enters successfully (i.e., “acknowledge”: true) and also assigns us an automatically created id. It is the special feature provided by MongoDB that every document provided a unique id and generally, this id is created automatically, but you are allowed to create your own id (must be unique).  

Document

In MongoDB, the data records are stored as BSON documents. Here, BSON stands for binary representation of JSON documents, although BSON contains more data types as compared to JSON. The document is created using field-value pairs or key-value pairs and the value of the field can be of any BSON type. 

Syntax:  

{ 
field1: value1
field2: value2
....
fieldN: valueN
}

Naming restriction of fields:

Before moving further first you should learn about the naming restrictions for fields: 

  • The field names are of strings.
  • The _id field name is reserved to use as a primary key. And the value of this field must be unique, immutable, and can be of any type other than an array.
  • The field name cannot contain null characters.
  • The top-level field names should not start with a dollar sign ($).

Document Size: The maximum size of the BSON document is 16MB. It ensures that the single document does not use too much amount of RAM or bandwidth(during transmission). If a document contains more data than the specified size, then MongoDB provides a GridFS API to store such type of documents. 

Important Notes –  

  • A single document may contain duplicate fields.
  • MongoDB always saves the order of the fields in the documents except for the _id field (which always comes in the first place) and the renaming of fields may change the order of the fields in the documents.
  • _id Field: In MongoDB, every document store in the collection must contain a unique _id field it is just like a primary key in a relational database. The value of the _id field can be set by the user or by the system (if the user does not create an _id field, then the system will automatically generate an ObjectId for _id field). 
    • When you create a collection MongoDB automatically creates a unique index on the _id field.
    • The _id field is the first field of every document.
    • The value of the _id field can be of any BSON type except arrays.
    • The default value of the _id field is ObjectId.

Example #1:  

Image

Here, name, branch, course, and paid field contain values of string type. amount field contains the value of integer type and _id field is generated by the system. 

Example #2:  

Image

Here, the _id field is created by the user. 

Tip: When you paste data in the functions always use close parenthesis after pasting the data into the function. If you use close parenthesis before pasting data in the function, then you will get an error.
 



Previous Article
Next Article

Similar Reads

How to Delete a Document From MongoDB Collection using NodeJS?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. This means that MongoDB isn’t based on a table-like relational database structure but provides an altogether different mechanism for data storage and retrieval. This storage format is called BSON ( similar to JSON format)
4 min read
How to Insert a Document into a MongoDB Collection using Node.js?
MongoDB, a popular NoSQL database, offers flexibility and scalability for handling data. If you're developing a Node.js application and need to interact with MongoDB, one of the fundamental operations you'll perform is inserting a document into a collection. This article provides a step-by-step guide on how to accomplish this using Node.js. Prerequ
5 min read
How to Create Database and Collection in MongoDB
MongoDB is a widely used NoSQL database which is used for its flexibility and scalability in managing data. Creating a database in MongoDB is a simple process using the use command. In this article, we'll explore how to create a database, create collections, and insert documents into collections in MongoDB. Creating a Database and Collection in Mon
3 min read
How to sort collection of MongoDB Database in ascending order using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON f
2 min read
How to sort collection of MongoDB Database in descending order using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON f
2 min read
How to Copy a Collection From One Database to Another in MongoDB?
Effective data management is crucial for MongoDB-dependent applications. As databases grow, the need to transfer collections between databases arises. This can be for creating development or testing environments, migrating data, or archiving historical information. MongoDB provides built-in capabilities and tools to simplify this process, offering
6 min read
Defining, Creating and Dropping a MongoDB collection
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. DocumentIt is the basic unit of MongoDB and a single reco
2 min read
How to rename the collection name of MongoDb using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON f
2 min read
How to drop collection in MongoDb using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON f
2 min read
How to create new Collection in MongoDB using Node.js ?
MongoDB the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON (similar to JSON for
1 min read
How to count total number of documents in MongoDB Collection using Node.js ?
MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. Installing module: You can install mongodb module using
1 min read
How to add unique constraint in collection of MongoDB using Node.js?
Mongoose module is one of the most powerful external modules of the node.js.Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server. Mongoose module provides several functions in order to manipulate the documents of the collection of the MongoDB database. Un
2 min read
How to add range in the Collection of Mongodb using Node.js ?
Mongoose.module is one of the most powerful external module of the node.js.Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server.Mongoose module provides several functions in order to manipulate the documents of the collection of the MongoDB database (Refe
2 min read
How to add Timestamp in Mongodb Collection using Node.js ?
Timestamp: With the help of timestamp document in the collection of the MongoDB can be differentiated on the basis of time. We can add Timestamp in Mongodb Collection in Node.js using the following approach: Installing Module: Install the mongoose module using the following command: npm install mongooseProject Structure: Our project structure will
1 min read
JUnit Test Execution For a MongoDB Collection using Maven
MongoDB is a NoSQL versatile database and it is widely used in software industries. Wherever there is no strict relational database relationship is necessary and also if there are chances of fetching the document often, it is always good to go with MongoDB. In this article, let us see the ways of Connecting to MongoDB,Creating collection,Inserting
4 min read
How to Sort a Collection by Date in MongoDB?
In MongoDB, sorting collections by date is a common requirement for many applications. Sorting by date allows us to display data in reverse order, making it easier for users to understand and analyze. In this article, we will explore different approaches to sorting collections by date in MongoDB, using various techniques and methods along with exam
3 min read
How to Retrieve only the Queried Element in an Object Array in MongoDB Collection
In MongoDB, retrieving specific elements from an object array within a document is a common requirement, especially when dealing with complex data structures. MongoDB provides powerful query operators to filter and retrieve only the elements that match certain criteria within an array. This capability is particularly useful when we need to extract
4 min read
How to Changing the Primary Key in MongoDB Collection
In MongoDB, the primary key uniquely identifies each document within a collection. While MongoDB automatically assigns a primary key using the _id field, there may be scenarios where we need to change the primary key to a different field or value. In this article, we'll explore how to change the primary key in a MongoDB collection by providing deta
5 min read
How to Use MongoDump for a Single Collection Backup in MongoDB
Backing up MongoDB data is important for ensuring data integrity and disaster recovery. mongodump is a MongoDB utility that allows us to create backups of our databases. In this article, we'll explore how to use Mongodump specifically for backing up a single collection. We'll cover the concepts behind mongodump, and provide detailed examples to und
3 min read
How to Get the Latest Record from MongoDB Collection
Retrieving the latest record from a MongoDB collection is a common task in many applications. Whether we are building a messaging app, tracking sensor data, or managing user activity getting the most recent data entry is essential for real-time analytics and decision-making. In this article, we'll explore different methods to fetch the latest recor
4 min read
Collection-Level Access Control in MongoDB
In modern database management, fine-grained access control is essential to meet the complex security requirements of organizations. MongoDB, a leading NoSQL database, offers robust mechanisms for managing permissions at various levels, including collection-level access control. This feature enables administrators to specify who can do what at the l
4 min read
MongoDB Remove() Method - db.Collection.remove()
The MongoDB remove() method is used to remove documents from a collection based on specified criteria. It can remove one or all documents matching the query expression. This method offers flexibility in deletion and supports various options like removing only one document and specifying a write concern. In this article, We will learn about MongoDB
4 min read
How Many Documents are in a MongoDB Collection?
In MongoDB, data is organized into collections and documents. A collection is a grouping of documents similar to a table in a relational database but without a fixed schema it allowing for flexible data structures. Documents on the other hand are JSON-like structures composed of key-value pairs which can vary within the same collection. In this art
6 min read
MongoDB - db.collection.findOneAndReplace() Method
The findOneAndReplace() method in MongoDB is a powerful tool for finding and replacing a single document within a collection. This method replaces the first document that matches the specified criteria with a new one. By default, it returns the original document but this can be configured to return the new document. In this article, We will learn a
5 min read
How to Listen for Changes to a MongoDB Collection?
Tracking changes in MongoDB is essential for applications requiring real-time updates or synchronization with the database. Traditionally, this was achieved through polling, which could be inefficient. MongoDB offers more effective methods to track changes including Change Streams, the watch() method and Oplog Tailing. In this article, We will lear
6 min read
How to Add a Column in MongoDB Collection?
In MongoDB, the ability to add new fields to collections without restructuring the entire schema is a powerful feature. Whether we are adapting to changing requirements or enhancing existing data, MongoDB offers several methods through easily we can easily add new fields to our collections. In this article, we'll learn about How to add a column in
4 min read
MongoDB updateMany() Method - db.Collection.updateMany()
MongoDB updateMany method is a powerful feature used to update multiple documents in a collection that match a specified filter. This method allows us to apply updates to all documents that meet the criteria defined in the filter. By using MongoDB updateMany developers can efficiently perform bulk update operations. In this article, We will learn a
4 min read
MongoDB insertMany() Method - db.Collection.insertMany()
MongoDB insertMany() method is a powerful tool for inserting multiple documents into a collection in one operation. This method is highly versatile, allowing for both ordered and unordered inserts, and provides options for customizing the write concern. In this article, We will learn about insertMany() in MongoDB by including its syntax, parameters
7 min read
MongoDB count() Method - db.Collection.count()
MongoDB count() method is a powerful tool for counting documents that match a specified query in a collection. It offers flexibility in filtering documents and can be used to quickly retrieve counts of documents based on various criteria. In this article, We will learn about the MongoDB count() Method by understanding various examples in detail. Mo
4 min read
MongoDB insertOne() Method - db.Collection.insertOne()
insertOne() method in MongoDB is a powerful tool for inserting a single document into a collection. This method ensures that each document added to the collection is assigned a unique _id if one is not provided, thus maintaining the integrity and uniqueness of the data. In this article, We will learn about the MongoDB insertOne() Method by understa
4 min read
three90RightbarBannerImg