Home Database Mysql Tutorial MongoDB Advanced Chapter Dynamic Field Design

MongoDB Advanced Chapter Dynamic Field Design

May 17, 2018 pm 02:00 PM
mongodb Field design

This article mainly introduces to you the relevant information of MongoDB advanced dynamic field design. The introduction in the article is very detailed and has certain reference and learning value for everyone. Friends who need it can follow the small Let’s learn together.

This article mainly introduces relevant information about MongoDB dynamic field design. It is shared for everyone's reference and study. Friends who need it can take a look at the detailed introduction.

Suitable for readers

  • MongoDB developers

Basic requirements

Product: "We want to add a great feature to the existing form that allows users to add the fields they want"

Technical goal version 1

Storage dynamic form data (new fields do not need to modify the Schema)

Let’s talk about it first Let’s talk about what kinds of indexes are supported by MongoDB

Common field index

// 假如我们的文档长这样
{
 "name": "MongoDB",
 "age": 5
}

// 对age字段建立索引
{
 "age": 1
}
Copy after login

Embedded document index

// 假如我们的文档长成了Object
{
 "person": {
  "age": 2,
  "name": "MongoDB"
 }
}

//对person.age字段建立索引
{
 "person.age": 1
}
Copy after login

ArrayDocument Index

// 假如我们的文档长成了数组
{
 "persons": [
  { "name": "MongoDB", age: 5},
  { "name": "MySQL", age: 20}
 ]
}
//对persons.age字段建立索引
{
 "persons.age": 1
}
Copy after login

It seems that none of the above can achieve the function of dynamically adding fields

Programmer The following conversation took place between A and programmer S:

  • Programmer A: "Then we need to add another collection to store dynamic content"

  • programmerS: "But MongoDB's support for related queries is very weak, and it can't even be related to sorting. If future products say that they will add sorting and filtering functions, we will be confused☹️, ugh~ If we had known this, we would not have used MongoDB. "

Re-examine the requirements

  • Store dynamic form data

  • Need to support filtering and sorting

Technical goal version2

Add fields while also being able to index

Solution

  • Use arrays to store dynamic fields

  • Add description collection To record the user's form configuration

The storage structure is as follows:

//描述collection 
{
 "_id":"描述id",
 "type":"类型",
 "text": "订单名称",
 "default": "Default Name",
}

// 原本的表单增加字段form用来存储动态数据
{
 "_id": "",
 "name": "一个好名字",
 "form":[
 { "_id":"描述_id", "value": 10},
 { "_id":"描述_id", "value": "我的好伙伴"},
 ]
}
Copy after login

Attention!!! When the user When adding n fields, describe the collection and add n documents at the same time

How to query, sort and filter

// 比如用户增加了2个字段
// 现在要对字段1进行排序
db.items.find().sort({"form.0.value":1})
// 对字段2进行筛选
db.items.find({"form.1.value":"我的好伙伴"})
Copy after login

As can be seen from the above example, even if the user does not fill in the field value, but We still need to store null values ​​for it to ensure that the nth field under all our Document forms is the same Control, so that we can filter and sort the fields. , and indexable

Continue to drill down

products: "We need to allow users to add drop-down boxes and multi-select boxes, as well as Filter sorting"

Programmer: "Fxxx"

So how should such data be stored?

Solution As follows:

Our value is stored in the binary format of 1,2,4,8...

such as

If the user selects the first item of the radio button, 1 is stored, the second item is stored with 2, and the third item is stored with 4

The user selects the first item + third item of the multi-select box: Then save 5, (1+4)

MongoDB provides us with a powerful Aggregate function, which includes the Bitwise Query Operators function, including $bitsAllSet, $bitsAnySet, $bitsAllClear, $bitsAnyClear

db.items.aggregate([
 {
  "$match": {
  "$elemMatch": {
   "描述id": "id",
   "value": { $bitsAnySet: [ 1, 5 ] }
  }
 }}
])
Copy after login

The above completes the various requirements for using MongoDB dynamic field design

The above is the detailed content of MongoDB Advanced Chapter Dynamic Field Design. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Which version is generally used for mongodb? Which version is generally used for mongodb? Apr 07, 2024 pm 05:48 PM

It is recommended to use the latest version of MongoDB (currently 5.0) as it provides the latest features and improvements. When selecting a version, you need to consider functional requirements, compatibility, stability, and community support. For example, the latest version has features such as transactions and aggregation pipeline optimization. Make sure the version is compatible with the application. For production environments, choose the long-term support version. The latest version has more active community support.

Retro trend! HMD and Heineken jointly launch flip phone: transparent shell design Retro trend! HMD and Heineken jointly launch flip phone: transparent shell design Apr 17, 2024 pm 06:50 PM

According to news on April 17, HMD teamed up with the well-known beer brand Heineken and the creative company Bodega to launch a unique flip phone - The Boring Phone. This phone is not only full of innovation in design, but also returns to nature in terms of functionality, aiming to lead people back to real interpersonal interactions and enjoy the pure time of drinking with friends. Boring mobile phone adopts a unique transparent flip design, showing a simple yet elegant aesthetic. It is equipped with a 2.8-inch QVGA display inside and a 1.77-inch display outside, providing users with a basic visual interaction experience. In terms of photography, although it is only equipped with a 30-megapixel camera, it is enough to handle simple daily tasks.

The difference between nodejs and vuejs The difference between nodejs and vuejs Apr 21, 2024 am 04:17 AM

Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

ZTE 5G portable Wi-Fi U50S goes on sale for NT$899 at first launch: top speed 500Mbps ZTE 5G portable Wi-Fi U50S goes on sale for NT$899 at first launch: top speed 500Mbps Apr 26, 2024 pm 03:46 PM

According to news on April 26, ZTE’s 5G portable Wi-Fi U50S is now officially on sale, starting at 899 yuan. In terms of appearance design, ZTE U50S Portable Wi-Fi is simple and stylish, easy to hold and pack. Its size is 159/73/18mm and is easy to carry, allowing you to enjoy 5G high-speed network anytime and anywhere, achieving an unimpeded mobile office and entertainment experience. ZTE 5G portable Wi-Fi U50S supports the advanced Wi-Fi 6 protocol with a peak rate of up to 1800Mbps. It relies on the Snapdragon X55 high-performance 5G platform to provide users with an extremely fast network experience. Not only does it support the 5G dual-mode SA+NSA network environment and Sub-6GHz frequency band, the measured network speed can even reach an astonishing 500Mbps, which is easily satisfactory.

Teclast M50 Mini tablet is here: 8.7-inch IPS screen, 5000mAh battery Teclast M50 Mini tablet is here: 8.7-inch IPS screen, 5000mAh battery Apr 04, 2024 am 08:31 AM

According to news on April 3, Taipower’s upcoming M50 Mini tablet computer is a device with rich functions and powerful performance. This new 8-inch small tablet is equipped with an 8.7-inch IPS screen, providing users with an excellent visual experience. Its metal body design is not only beautiful but also enhances the durability of the device. In terms of performance, the M50Mini is equipped with the Unisoc T606 eight-core processor, which has two A75 cores and six A55 cores, ensuring a smooth and efficient running experience. At the same time, the tablet is also equipped with a 6GB+128GB storage solution and supports 8GB memory expansion, which meets users’ needs for storage and multi-tasking. In terms of battery life, M50Mini is equipped with a 5000mAh battery and supports Ty

Honor Magic V3 debuts AI defocus eye protection technology: effectively alleviates the development of myopia Honor Magic V3 debuts AI defocus eye protection technology: effectively alleviates the development of myopia Jul 18, 2024 am 09:27 AM

According to news on July 12, the Honor Magic V3 series was officially released today, equipped with the new Honor Vision Soothing Oasis eye protection screen. While the screen itself has high specifications and high quality, it also pioneered the introduction of AI active eye protection technology. It is reported that the traditional way to alleviate myopia is "myopia glasses". The power of myopia glasses is evenly distributed to ensure that the central area of ​​​​sight is imaged on the retina, but the peripheral area is imaged behind the retina. The retina senses that the image is behind, promoting the eye axis direction. grow later, thereby deepening the degree. At present, one of the main ways to alleviate the development of myopia is the "defocus lens". The central area has a normal power, and the peripheral area is adjusted through optical design partitions, so that the image in the peripheral area falls in front of the retina.

Where is the database created by mongodb? Where is the database created by mongodb? Apr 07, 2024 pm 05:39 PM

The data of the MongoDB database is stored in the specified data directory, which can be located in the local file system, network file system or cloud storage. The specific location is as follows: Local file system: The default path is Linux/macOS:/data/db, Windows: C:\data\db. Network file system: The path depends on the file system. Cloud Storage: The path is determined by the cloud storage provider.

What are the advantages of mongodb database What are the advantages of mongodb database Apr 07, 2024 pm 05:21 PM

The MongoDB database is known for its flexibility, scalability, and high performance. Its advantages include: a document data model that allows data to be stored in a flexible and unstructured way. Horizontal scalability to multiple servers via sharding. Query flexibility, supporting complex queries and aggregation operations. Data replication and fault tolerance ensure data redundancy and high availability. JSON support for easy integration with front-end applications. High performance for fast response even when processing large amounts of data. Open source, customizable and free to use.

See all articles