Foreign Keys in MongoDB

Tahseen Tauseef May 04, 2022
  1. Foreign Key
  2. MongoDB References
  3. Create Virtual Foreign Keys in MongoDB
  4. Conclusion
Foreign Keys in MongoDB

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

MongoDB, unlike traditional RDBMS, necessitates a distinct approach to database design. But, overall, the database is easier to scale because it doesn’t impose many restrictions.

Foreign Key

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

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

A foreign key can be used to accomplish this:

Foreign Key

If we read the 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 of the cities in Pakistan with a single query.

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

We can also set null, which means that when data in the country database is deleted, the cities linked are set to null.

MongoDB References

Typically, MongoDB doesn’t work with the concept of foreign keys. However, relational databases can use foreign keys to visualize data from multiple collections simultaneously.

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

MongoDB offers two different ways of storing data in collections: denormalization and normalization.

Denormalization

In denormalization, the same collection contains a variety of data.

The sample below demonstrates how the addresses linked with each person have been embedded in the persons collection.

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

It is suitable for one-to-few. Its advantage is that there is no need to perform additional queries to another document.

However, it cannot manage the entity of embedded documents individually.

Normalization

In normalization, different data is stored in various collections. The process is similar to storing data in relational databases, but instead of tables, we use collections.

In MongoDB, the references are primarily used for the normalization process. The references from the children’s table (usually an Object ID) are then embedded in the parent table.

When reading the information, the user has to perform several 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 the so-called foreign key in MongoDB. However, you need to maintain the data integrity BY YOURSELVES.

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 _id of courses. It is pretty simple to define a one-to-many relationship.

However, if you want to retrieve the course names of student Haris, you will need to perform another operation to retrieve the courses document via _id.

If the course chem101 is removed, we need to perform another operation to update the courses field in the students document.

Create Virtual Foreign Keys in MongoDB

DbSchema saves the schema’s local image in the model file. This means you can work on the project offline without needing to connect to the database.

After reconnecting, you can compare and synchronize the differences between the database and your local project file. You can also construct virtual foreign key relationships with a project file.

These foreign keys can only be used in DbSchema, and they do not affect the database.

Foreign keys can be made quickly and easily. Take the cities and countries collections, for example. For their reference, both will have a common field called “country id.”

Foreign Key 2

Drag and drop one column over the other to create a foreign key. This will create a new window where you may give the foreign key a description and add additional fields.

Use Virtual Foreign Keys for Faster Data Browsing in MongoDB

You may browse the data from your collections using the virtual foreign key. Additionally, the Relational Data Editor allows you to simultaneously browse data from many collections.

You can quickly browse the cities connected with the countries using the foreign key.

Conclusion

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

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

Related Article - MongoDB Database