JIYIK CN >

Current Location:Home > Learning > DATABASE > MongoDB >

Foreign Keys in MongoDB

Author:JIYIK Last Updated:2025/04/10 Views:

MongoDB is a well-known database that works without a schema. Instead, it uses JSON-like files to save data and does not impose any structure.

MongoDB requires a unique approach to database design, unlike traditional RDBMS. However, overall, the database is easier to scale because it doesn't impose as many restrictions.


Foreign Keys

A foreign key is a column or set of columns that links two tables. It contains primary key columns in the parent table that link to other columns in the child table.

Take for example two tables: countries and cities. We want to link these two tables together so that each city is associated with the appropriate country.

This can be done using foreign keys:

Foreign Keys

If we read data from the city table in the example above, we can see that each city has an associated country_id. This will allow you to search for all cities in Pakistan with a single query.

When creating a foreign key, we can specify what should happen if the data is modified or destroyed. For example, we can choose to cascade, which means that if a country is eliminated, all cities associated with it are also eliminated.

We can also set it to null, that is, when deleting the data in the country database, the linked city is set to null.


MongoDB Reference

Generally, MongoDB does not use the concept of foreign keys. However, relational databases can use foreign keys to visualize data from multiple collections at the same time.

MongoDB also stores data differently. For example, instead of using tables, columns, and rows, MongoDB uses collections, objects, and fields.

MongoDB provides two different ways to store data in a collection: denormalized and normalized.

Denormalization

In denormalization, the same collection contains multiple types of data.

The following example shows how to embed the address linked to each person into a people collection.

> db.persons.findOne()
{
    name: 'Ali Ikram',
    addresses : [
        { street: '123 PWD', city: 'Rawalpindi', cc: 'PAK' },
        { street: '123 ABC', city: 'Faisalabad', cc: 'PAK' }
    ]
}

Suitable for one-to-many. Its advantage is that it does not require an additional query for another document.

However, it cannot manage entities embedded in documents independently.

Normalization

In normalization, different data is stored in different collections. This process is similar to storing data in a relational database, but we use collections instead of tables.

In MongoDB, references are primarily used for the normalization process. A reference (usually an object ID) from a child table is then embedded into the parent table.

When reading information, users must perform multiple queries to retrieve data from multiple collections.

For example, we will take the following two collections, students and courses. A course will contain many students referenced in the courses collection.

You can define so-called foreign keys in MongoDB. However, you need to maintain data integrity yourself.

example:

students
{
    _id: ObjectId(...),
    name: 'Haris',
    courses: ['chem101', 'chem102']   // <= ids of the courses
}

courses
{
    _id: 'chem101',
    name: 'Chemistry 101',
    description: 'Introduction to Chemistry'
}

The courses field contains the courses _id. Defining a one-to-many relationship is very simple.

However, if you want to retrieve the course titles of student Haris, you need to perform another operation to _idretrieve the course document through .

If the course chem101 is deleted, we need to perform another operation to update the course field in the student document.


Creating Virtual Foreign Keys in MongoDB

DbSchema saves a local image of the schema in a model file. This means you can work on your project offline without connecting to the database.

After reconnecting, you can compare and synchronize the differences between the database and the local project file. You can also build virtual foreign key relationships using the project file.

These foreign keys can only be used in DbSchema and have no effect on the database.

Foreign keys can be made quickly and easily. Take a collection of cities and countries as an example. For reference, both have a common field called "CountryID".

Foreign Key 2

Drag and drop one column onto another to create a foreign key. This will create a new window where you can give the foreign key a description and add additional fields.

Navigate faster in MongoDB using virtual foreign keys

You can use virtual foreign keys to browse the data in your collections. In addition, the relational data editor allows you to browse data from multiple collections simultaneously.

You can use foreign keys to quickly browse cities connected to countries.


Summarize

With this MongoDB tutorial article, you learned how to visualize MongoDB collections as diagrams and build virtual foreign keys using DbSchema. You should also now be able to browse data from different collections simultaneously.

In addition, virtual foreign keys will only be saved in local project files and will not affect the database.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

$ne operator in MongoDB

Publish Date:2025/04/11 Views:84 Category:MongoDB

This article will discuss how the $ne operator works in MongoDB. In addition, we will list its differences from the $not operator. $ne operator in MongoDB $ne is an operator in MongoDB that stands for not equal to. This will compare the val

MongoDB $Set Operator

Publish Date:2025/04/11 Views:159 Category:MongoDB

With the help of this article, you will learn how to use $set the operator to partially update objects in MongoDB so that the new object overlaps/merges with the existing object. The $set operator replaces the value of a field with a given

Difference between $push and $addToSet in MongoDB

Publish Date:2025/04/11 Views:63 Category:MongoDB

This article explains the operators in MongoDB. What is the purpose of $push and $addToSet operators. Furthermore, the difference between these two operators is given in the code snippet. This article discusses the following topics. Operato

Sort a collection by date in MongoDB

Publish Date:2025/04/11 Views:64 Category:MongoDB

In this MongoDB tutorial, the problem of sorting a collection in MongoDB is discussed. The different ways to sort a collection in the database are briefly explained. Using sort() function in MongoDB This problem is solved using the MongoDB

Counting records in MongoDB

Publish Date:2025/04/11 Views:146 Category:MongoDB

This article discusses operators in MongoDB, aggregation operators, and different ways to calculate the total number of records. Operations in MongoDB CRUD operations are a user interface concept that allows users to browse, search, and cha

Pretty printing in MongoDB

Publish Date:2025/04/11 Views:150 Category:MongoDB

This article will discuss how to use pretty printing in MongoDB to display formatted results. Pretty printing in MongoDB A cursor is an object that allows programmers in the Mongo world to iterate over documents in a Mongo collection. Altho

MongoDB Adding Elements to an Array

Publish Date:2025/04/11 Views:136 Category:MongoDB

This article will cover the various ways to add to an array in MongoDB. Adding to an array in MongoDB Use the $push operator to add values ​​to an array The $push operator is one of the various array update operators provided by MongoDB

MongoDB Search by ID

Publish Date:2025/04/11 Views:131 Category:MongoDB

The following article provides an overview of MongoDB find by Id() method. MongoDB provides a find by Id() function which can retrieve documents matching a user id. To use search by Id() in MongoDB, you need to use the find() function. If n

MongoDB starts with a query

Publish Date:2025/04/10 Views:195 Category:MongoDB

In this MongoDB article, users will learn how to start queries using $regex. It provides regular expression functionality for pattern matching strings in queries. MongoDB starts querying using $regex If you want to use $regex , use one of t

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial