Defining schema in MongoDB
This article will discuss the MongoDB Schema and how to define it.
Schema in MongoDB
The structure and content of the data is defined by a Schema , which is a JSON object. Realm's BSON schema extends the JSON Schema standard and can be used to design your application's data model and validate documents when they are created, modified, or deleted.
Schemas represent different types of data, rather than precise values. Realm supports many built-in schema types. Primitives such as text and numbers and structure types such as objects and arrays can be combined to form schemas that represent custom object types.
For example, given below is a basic schema about cars and some car object data that conforms to the schema.
Schema:
{
"title": "car",
"required": [
"_id",
"year",
"make",
"model",
"kilometers"
],
"properties": {
"_id": { "bsonType": "objectId" },
"year": { "bsonType": "string" },
"make": { "bsonType": "string" },
"model": { "bsonType": "string" },
"kilometers": { "bsonType": "number" }
}
}
Objects:
{
"_id": ObjectId("5af712eff26b29dc5c51c60f"),
"year": "2022",
"make": "Honda",
"model": "Civic",
"kilometers": 123
}
{
"_id": ObjectId("5af714eff24b294c5251cf04"),
"year": "2016",
"make": "Honda",
"model": "City",
"kilometers": 135794
}
A schema is a specification of your application's data model. Realm provides you with additional tools and services to work with data that conforms to the schema after you define your data.
Many application services in Realm use Schema:
- To synchronize data between Realm and MongoDB Atlas, Realm Sync uses schemas. Depending on your schema, it can also develop an idiomatic SDK object model for you.
- The GraphQL API automatically consumes the schema to generate a GraphQL schema that automatically contains types, queries, and mutations. Custom resolvers that reference types defined by the schema can be added to your application's API.
- Before and after each request, data access rules ensure that data conforms to your schema. In addition, if any document fails validation, Realm blocks or rolls back the entire request.
Considerations for designing schemas in MongoDB
- Design your schema according to user requirements.
- If you use these objects together, merge them into one document. If necessary, separate them (but make sure they don't need to be connected).
- Data is copied (but limitedly), because disk space is cheaper than computation time.
- Add it when you write, not when you read.
- Optimize your schema for the most common use cases.
- Do complex aggregations in your schema.
Here is an example to explain this:
Suppose a client needs to design a database for his blog or website and see the difference between RDBMS and MongoDB schema design. The website has the following requirements.
- Each post has a unique title, description, and URL.
- Each post can have one or more tags.
- Each post has the name of the poster and the total number of likes.
- Each post contains the user comment along with his/her name, message, data time and number of likes.
- On each post, there can be no or more comments.
In the RDBMS schema, the design for the above requirements will contain at least three tables.
Whereas in MongoDB schema, the design would have a collection posts and the following structure:
{
_id: POST-ID
title: TITLE-OF-POST,
description: POST-DESCRIPTION,
by: POST-BY,
url: URL-OF-POST,
tags: [TAG1, TAG2],
likes: TOTAL-LIKES,
comments: [
{
user: 'COMMENT-BY',
message: TEXT,
dateCreated: DATE-TIME,
like: LIKES
},
{
user: 'COMMENT-BY',
message: TEXT,
dateCreated: DATE-TIME,
like: LIKES
}
]
}
So, in RDBMS, you have to combine three tables to display the data; however, in MongoDB, the data is displayed in only one collection.
Defining Schemas in MongoDB
Additional patterns for properties of a specific type can be found in the root-level collection pattern. Each root-level pattern is an object pattern, as follows:
{
"bsonType": "object",
"title": "<Type Name>",
"required": ["<Required Field Name>", ...],
"properties": {
"<Field Name>": <Schema>
}
}
Users can configure the properties of an object using any of the following supported schema types:
- Object
- Array
- String
- Boolean
- ObjectId
- Binary Data
- Mixed
- Set
- Dictionary
Implementing Schemas Using MongoDB Realms
All write operations (inserts, updates, and deletes) on a MongoDB collection are validated by MongoDB Realm against the collection schema.
It also checks each document before and after each request to ensure that all properties are consistent with the schema and that no invalid changes have been made.
Realm checks the results of all document writes and compares them to the schema before submitting write operations to your cluster.
If the result of any write operation in the request does not conform to the schema without making any changes to the request, MongoDB Realm sends an error to the user.
An example is given below. The collection has the following schema:
{
"title": "person",
"properties": {
"_id": {"bsonType": "objectId" },
"name": {"bsonType": "string" }
}
}
A user with full access to all fields wants to change the Name field in a specific document. They ask the following:
collection.updateOne(
{ "_id": BSON.ObjectId("5ae782e48f25b9dc5c51c4d0") },
{ "$set": { "name": 22 } }
)
The query attempts to set the name value to the number 22. However, the schema specifies that the value is a string.
Even if the user is authorized to update the document, MongoDB Realm will reject the write operation because the write would not conform to the schema.
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.
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