亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Database Mysql Tutorial Mysql for Mongoose developer.

Mysql for Mongoose developer.

Dec 24, 2024 pm 03:41 PM

Mysql  for Mongoose developer.

Introduction

  • I don't care.
  • MySQL is a relational database management system (RDBMS). It is an open-source, multi-user, multi-threaded database system that allows for storing and managing structured data in tables. It uses the Structured Query Language (SQL) to manage and manipulate data.

Key Features of MySQL:

  • Open Source
  • Cross-Platform
  • Relational Database: MySQL is based on a relational database model, which stores data in tables (also known as relations).
  • High Performance: It is optimized for speed and can handle a large amount of data efficiently.
  • ACID Compliant: MySQL supports the ACID (Atomicity, Consistency, Isolation, Durability) properties, ensuring that database transactions are processed reliably.
    • Atomicity ensures that a transaction is treated as a single, indivisible unit. Either all of the operations within a transaction are completed successfully, or none of them are applied. In other words, a transaction is atomic: it is "all or nothing."
    • Consistency ensures that a transaction takes the database from one valid state to another valid state. After a transaction, all data must be in a consistent state, adhering to all defined rules, constraints, and relationships.
    • Isolation ensures that transactions are executed in isolation from one another, even if they occur concurrently. Each transaction should be executed as if it is the only transaction being processed, preventing interference from other transactions.
    • Durability ensures that once a transaction is committed, it is permanent, even in the case of system failures like power outages or crashes. The changes made by the transaction are saved to disk and will survive any subsequent failures.
  • Multi-User Access: MySQL allows multiple users to access the database simultaneously without affecting performance.

SQL Keywords

CREATE

  1. CREATE DATABASE
    • The CREATE DATABASE command is used to create a new database. In Mongoose, you don't need to explicitly create a database; it is automatically created when you connect to the database.
// DB is created if it doesn't exist
mongoose.connect('mongodb://localhost/my_database');
CREATE DATABASE my_database;
  1. USE DATABASE
    • The USE DB_NAME is used to select the database to use. In Mongoose, this is handled by the connection string.
mongoose.connect('mongodb://localhost/my_database');
USE my_database;
  1. CREATE TABLE
    • The CREATE TABLE command is used to create a new table in the database. In Mongoose, this is similar to creating a new collection.
// DB is created if it doesn't exist
mongoose.connect('mongodb://localhost/my_database');
CREATE DATABASE my_database;
  1. CREATE INDEX
    • The CREATE INDEX command is used to create an index on a table to improve query performance. In MongoDB, this is the same.
mongoose.connect('mongodb://localhost/my_database');
USE my_database;

DESCRIBE

  • Used in SQL to view the structure of a table (its columns, data types, constraints, etc.). Mongoose Example: In MongoDB, there isn't a direct equivalent to DESCRIBE. However, you can inspect a schema programmatically.
mongoose.model('User', UserSchema);
CREATE TABLE Users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE
);

INSERT

  • The INSERT INTO command is used to insert new rows in a table. In mongoose you would insert a new document into a collection/(Model).
UserSchema.index({ email: 1 }); // Unnamed Index
UserSchema.index({ email: 1 }, { name: 'idx_email' }); // Named Index
-- Syntax: CREATE INDEX index_name ON table_name (column_name);
CREATE INDEX idx_email ON Users (email); -- Named Index
CREATE INDEX ON Users (email); -- Unnamed Index

SELECT

  • The SELECT statement in SQL is used to retrieve data from a database. In Mongoose, this is equivalent to using the .find() method to query a collection.
console.log(UserSchema.paths);
// Outputs details about the schema fields and types
DESCRIBE Users;

UPDATE

  • The UPDATE statement is used to modify the existing records in a table. In mongoose you use find and update or .update()
// In mongoose its equivalent to .save() or .create();
const newUser = new User({ name: 'John Doe', email: 'john@example.com' });
newUser.save()
INSERT INTO Users (name, email)
VALUES ('John Doe', 'john@example.com');

DELETE

  • The DELETE statement is used to delete existing records in a table. In mongoose we'd use deleteOne, deleteMany or find and delete.
const users = await User.find(); // Fetches all users
const { name, email } = await User.findById(1); // Fetches user with id = 1
SELECT * FROM Users; -- all users
SELECT name, email FROM Users WHERE id = 1; -- user of id 1

ALTER

  • The ALTER TABLE statement in SQL is used to modify the structure of an existing table (add column, drop column and modify column). In Mongoose, the equivalent operation would be modifying the schema to include the new field and then handling updates to existing documents if necessary.
// update all user of name kb
const query = { name: "kb" };
User.update(query, { name: "thekbbohara" })
-- update all user of name kb
UPDATE Users
SET name = "thekbbohara", email = "thekbbohara@gmail.com"
WHERE name = "kb";

JOIN

  • A JOIN clause is used to combine rows from two or more tables, based on a related column between them. In MongoDB, joins are not natively supported like in relational databases. Instead, you typically use aggregation pipelines like $lookup for similar functionality.
User.deleteOne({ _id: 1 })
// All users whose name is notKb will be deleted.
User.deleteMany({ name: "notKb" })

INNER JOIN

  • The INNER JOIN keyword selects records that have matching values in both tables.
DELETE FROM Users WHERE id = 1;
DELETE FROM Users WHERE name = "notKb"
-- All users whose name is notKb will be deleted.

LEFT JOIN

  • The LEFT JOIN keyword returns all records from the left table (table1), and the matching records (if any) from the right table (table2).
// Update the UserSchema to add the 'age' field
const UserSchema = new mongoose.Schema({
    name: String,
    email: String,
    age: Number, // New field
});

RIGHT JOIN

  • The RIGHT JOIN keyword returns all records from the right table (table2), and the matching records (if any) from the left table (table1).
-- Adds an 'age' column to the Users table
ALTER TABLE Users ADD age INT;

-- Delete 'Email' column from Users table
ALTER TABLE Users DROP COLUMN email;

-- Makes 'id' column unsigned and auto-incrementing
ALTER TABLE Users MODIFY COLUMN id INT UNSIGNED AUTO_INCREMENT;

CROSS JOIN

  • The CROSS JOIN keyword returns all records from both tables (table1 and table2).
// DB is created if it doesn't exist
mongoose.connect('mongodb://localhost/my_database');

DATATYPES

In MySQL there are three main data types: string, numeric, and date and time. But in MongoDB, there are a variety of data types, but they differ from those in MySQL. MongoDB uses BSON (Binary JSON) to store data, which supports a rich set of data types. Here's a comparison of common data types in MySQL and MongoDB:

String Data Types

MySQL MongoDB (BSON) Notes
CHAR, VARCHAR String Both store textual data. MongoDB's String is analogous to VARCHAR.
TEXT, TINYTEXT, etc. String No separate TEXT type in MongoDB; all textual data is stored as String.

Numeric Data Types

MySQL MongoDB (BSON) Notes
INT, SMALLINT, etc. NumberInt Represents 32-bit integers.
BIGINT NumberLong Represents 64-bit integers.
FLOAT, DOUBLE NumberDouble Represents floating-point numbers.
DECIMAL, NUMERIC String or custom MongoDB doesn't have an exact equivalent; use String for precision.

Date and Time Data Types

MySQL MongoDB (BSON) Notes
DATE Date Both store date-only values.
DATETIME, TIMESTAMP Date MongoDB stores both date and time as a Date object.
TIME String or custom MongoDB does not have a direct TIME type; store as String if needed.
YEAR String or Int Represented using String or NumberInt.

Boolean Data Types

MySQL MongoDB (BSON) Notes
BOOLEAN, TINYINT(1) Boolean Both store true/false values.

Binary Data Types

MySQL MongoDB (BSON) Notes
BLOB, TINYBLOB, etc. BinData MongoDB's BinData is used for storing binary data like files.

JSON/Array Data Types

MySQL MongoDB (BSON) Notes
JSON Object MongoDB natively stores JSON-like documents as Object.
N/A Array MongoDB has a native Array type for storing lists of values.

Other Data Types

MySQL MongoDB (BSON) Notes
ENUM String or custom Use a String field with validation for enumerated values.
SET Array Use an Array to represent sets of values.
N/A ObjectId Unique identifier type in MongoDB, typically used as a primary key.
N/A Decimal128 Used for high-precision decimal numbers in MongoDB.

PRIMARY KEY

  • Ensures that each row in a table has a unique identifier.
// DB is created if it doesn't exist
mongoose.connect('mongodb://localhost/my_database');
CREATE DATABASE my_database;

FOREIGN KEY

  • Ensures a column's values correspond to values in another table.
mongoose.connect('mongodb://localhost/my_database');
USE my_database;

Data Integrity and Constraints

  1. NOT NULL: Ensures that a column cannot have NULL values.
mongoose.model('User', UserSchema);
CREATE TABLE Users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE
);
  1. UNIQUE: Ensures that all values in a column are unique.
UserSchema.index({ email: 1 }); // Unnamed Index
UserSchema.index({ email: 1 }, { name: 'idx_email' }); // Named Index
-- Syntax: CREATE INDEX index_name ON table_name (column_name);
CREATE INDEX idx_email ON Users (email); -- Named Index
CREATE INDEX ON Users (email); -- Unnamed Index
  1. DEFAULT: Assigns a default value to a column if no value is provided.
console.log(UserSchema.paths);
// Outputs details about the schema fields and types
DESCRIBE Users;
  1. CHECK (MySQL 8.0 ): Ensures that the values in a column satisfy a given condition.
// In mongoose its equivalent to .save() or .create();
const newUser = new User({ name: 'John Doe', email: 'john@example.com' });
newUser.save()
INSERT INTO Users (name, email)
VALUES ('John Doe', 'john@example.com');
  1. AUTO_INCREMENT: Automatically generates a unique value for a column, often used for primary keys.
const users = await User.find(); // Fetches all users
const { name, email } = await User.findById(1); // Fetches user with id = 1
SELECT * FROM Users; -- all users
SELECT name, email FROM Users WHERE id = 1; -- user of id 1

That's all. You are good to go feel free to leave your feedback and you can get in touch with me here: thekbbohara

OH, by the way how do we setup Mysql.
I recommend using docker:

// update all user of name kb
const query = { name: "kb" };
User.update(query, { name: "thekbbohara" })
-- update all user of name kb
UPDATE Users
SET name = "thekbbohara", email = "thekbbohara@gmail.com"
WHERE name = "kb";

The above is the detailed content of Mysql for Mongoose developer.. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

PHP Tutorial
1488
72
Handling NULL Values in MySQL Columns and Queries Handling NULL Values in MySQL Columns and Queries Jul 05, 2025 am 02:46 AM

When handling NULL values ??in MySQL, please note: 1. When designing the table, the key fields are set to NOTNULL, and optional fields are allowed NULL; 2. ISNULL or ISNOTNULL must be used with = or !=; 3. IFNULL or COALESCE functions can be used to replace the display default values; 4. Be cautious when using NULL values ??directly when inserting or updating, and pay attention to the data source and ORM framework processing methods. NULL represents an unknown value and does not equal any value, including itself. Therefore, be careful when querying, counting, and connecting tables to avoid missing data or logical errors. Rational use of functions and constraints can effectively reduce interference caused by NULL.

Performing logical backups using mysqldump in MySQL Performing logical backups using mysqldump in MySQL Jul 06, 2025 am 02:55 AM

mysqldump is a common tool for performing logical backups of MySQL databases. It generates SQL files containing CREATE and INSERT statements to rebuild the database. 1. It does not back up the original file, but converts the database structure and content into portable SQL commands; 2. It is suitable for small databases or selective recovery, and is not suitable for fast recovery of TB-level data; 3. Common options include --single-transaction, --databases, --all-databases, --routines, etc.; 4. Use mysql command to import during recovery, and can turn off foreign key checks to improve speed; 5. It is recommended to test backup regularly, use compression, and automatic adjustment.

Calculating Database and Table Sizes in MySQL Calculating Database and Table Sizes in MySQL Jul 06, 2025 am 02:41 AM

To view the size of the MySQL database and table, you can query the information_schema directly or use the command line tool. 1. Check the entire database size: Execute the SQL statement SELECTtable_schemaAS'Database',SUM(data_length index_length)/1024/1024AS'Size(MB)'FROMinformation_schema.tablesGROUPBYtable_schema; you can get the total size of all databases, or add WHERE conditions to limit the specific database; 2. Check the single table size: use SELECTta

Handling character sets and collations issues in MySQL Handling character sets and collations issues in MySQL Jul 08, 2025 am 02:51 AM

Character set and sorting rules issues are common when cross-platform migration or multi-person development, resulting in garbled code or inconsistent query. There are three core solutions: First, check and unify the character set of database, table, and fields to utf8mb4, view through SHOWCREATEDATABASE/TABLE, and modify it with ALTER statement; second, specify the utf8mb4 character set when the client connects, and set it in connection parameters or execute SETNAMES; third, select the sorting rules reasonably, and recommend using utf8mb4_unicode_ci to ensure the accuracy of comparison and sorting, and specify or modify it through ALTER when building the library and table.

Aggregating data with GROUP BY and HAVING clauses in MySQL Aggregating data with GROUP BY and HAVING clauses in MySQL Jul 05, 2025 am 02:42 AM

GROUPBY is used to group data by field and perform aggregation operations, and HAVING is used to filter the results after grouping. For example, using GROUPBYcustomer_id can calculate the total consumption amount of each customer; using HAVING can filter out customers with a total consumption of more than 1,000. The non-aggregated fields after SELECT must appear in GROUPBY, and HAVING can be conditionally filtered using an alias or original expressions. Common techniques include counting the number of each group, grouping multiple fields, and filtering with multiple conditions.

Implementing Transactions and Understanding ACID Properties in MySQL Implementing Transactions and Understanding ACID Properties in MySQL Jul 08, 2025 am 02:50 AM

MySQL supports transaction processing, and uses the InnoDB storage engine to ensure data consistency and integrity. 1. Transactions are a set of SQL operations, either all succeed or all fail to roll back; 2. ACID attributes include atomicity, consistency, isolation and persistence; 3. The statements that manually control transactions are STARTTRANSACTION, COMMIT and ROLLBACK; 4. The four isolation levels include read not committed, read submitted, repeatable read and serialization; 5. Use transactions correctly to avoid long-term operation, turn off automatic commits, and reasonably handle locks and exceptions. Through these mechanisms, MySQL can achieve high reliability and concurrent control.

Connecting to MySQL Database Using the Command Line Client Connecting to MySQL Database Using the Command Line Client Jul 07, 2025 am 01:50 AM

The most direct way to connect to MySQL database is to use the command line client. First enter the mysql-u username -p and enter the password correctly to enter the interactive interface; if you connect to the remote database, you need to add the -h parameter to specify the host address. Secondly, you can directly switch to a specific database or execute SQL files when logging in, such as mysql-u username-p database name or mysql-u username-p database name

Managing Character Sets and Collations in MySQL Managing Character Sets and Collations in MySQL Jul 07, 2025 am 01:41 AM

The setting of character sets and collation rules in MySQL is crucial, affecting data storage, query efficiency and consistency. First, the character set determines the storable character range, such as utf8mb4 supports Chinese and emojis; the sorting rules control the character comparison method, such as utf8mb4_unicode_ci is case-sensitive, and utf8mb4_bin is binary comparison. Secondly, the character set can be set at multiple levels of server, database, table, and column. It is recommended to use utf8mb4 and utf8mb4_unicode_ci in a unified manner to avoid conflicts. Furthermore, the garbled code problem is often caused by inconsistent character sets of connections, storage or program terminals, and needs to be checked layer by layer and set uniformly. In addition, character sets should be specified when exporting and importing to prevent conversion errors

See all articles