In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
With the rapid development of the Internet industry, there are many different solutions for data storage and architecture optimization, such as relational database, non-relational database, data warehouse technology and so on. The emergence of more database products, for us to solve the problem of data storage, such as Redis cache, MySQL relational database, MongoDB document database, Hbase data warehouse and so on.
With the development of business, when optimizing the architecture, MongoDB is selected to store part of the data, as an operation and maintenance staff can only catch up to learn the relevant knowledge of operation and maintenance. The following documents are your own study notes on MongoDB database, which mainly have the following characteristics:
1. There are few theories, mainly practical operation.
2. Comparative study with relational database MySQL, mainly in some aspects of operation. As the saying goes, if there is no comparison, there will be no harm. The comparative study of two different types of databases will improve the learning efficiency better.
I. the operation of the library
MySQL and MongoDB have the following differences in the concepts of library, table and data. MySQL has the concepts of database Database, table table, data rows and rows, while MongoDB does not have the concepts of tables and rows, mainly including database Database, collection collections, and documents.
RDBMS vs NoSQL
RDBMS
-highly organized structured data
-structured query language (SQL) (SQL)
-data and relationships are stored in separate tables.
-data manipulation language, data definition language
-strict consistency
-basic transaction
NoSQL
-represents more than just SQL.
-No declarative query language
-there are no predefined patterns
-key-value pair storage, column storage, document storage, graphics database
-final consistency, not ACID attribute
-unstructured and unpredictable data
-CAP theorem
-High performance, high availability and scalability
1.1 View all databases (already exist)
# MySQLmysql > show databases +-+ | Database | +-+ | information_schema | | mysql | | performance_schema | | winner | +-+ 4 rows in set # MongoDB [root@iZ23t094y03Z ~] # mongoMongoDB shell version: 2.4 .14 browse to: test > show dbsshow dbscol 0.203125GBlocal 0.078125GBtest 0.203125GBwinner2 0.203125GB to view the current database mysql > select database () +-+ | database () | +-+ | NULL | +-+ 1 row in set (0.03 sec) mysql > use winnerDatabase changedmysql > select database (); +-+ | database () | +-+ | winner | +-+ 1 row in set (0.00 sec) # MongoDB > db db test
Note:
In MongoDB, when connecting to the database server, when the database name is not specified. The default test library, while MySQL is empty by default, we can only see the specific current database information when we switch to a specific database.
1.2 switching databases
When switching databases, the commands use use + database names, but there is still a big difference between the two. In MongoDB, if there is no database name entered, it will create a library name, while MySQL will report an error in all the current libraries without the database name you entered.
> show dbscol 0.203125GBlocal 0.078125GBtest 0.203125GBwinner2 0.203125GB > use winswitched to db win > db win#MySQLmysql > show databases +-+ | Database | +-+ | information_schema | | mysql | | performance_schema | | winner | +-+ 4 rows in set (0.00 sec) mysql > use win;ERROR 1049 (42000): Unknown database 'win'mysql >
1.3 create a database
MongoDB does not have a specific command to create a database. Generally, in the process of switching, if the database does not exist, it will create a new database, and there is a create database databasename statement in MySQL to create the database.
Mysql > use win;ERROR 1049 (42000): Unknown database 'win' # before creation mysql > create database win; # creation statement generally, we also specify the Query OK of the character set or something when we create it, 1 row affected (0.00 sec) mysql > show databases +-+ | Database | +-+ | information_schema | | mysql | | performance_schema | | win | | winner | +-+ 5 rows in set (0.00 sec) MongoDBuse DATABASE_NAME if the database does not exist To create a database, otherwise switch to the specified database.
1.4 Delete the database
After learning to create and switch, we don't want it anymore, so let's consider how to delete it. Delete the current library with db.dropDatabase () in MongoDB and delete the library you want to delete with drop database databasename; in MySQL.
MySQLmysql > create database winner2; # create library Query OK, 1 row affected (0.00 sec) mysql > use winner2; # switch library Database changedmysql > select database (); # View current library +-+ | database () | +-+ | winner2 | +-+ 1 row in set (0.00 sec) mysql > drop database winner2; # Delete winner2Query OK, 0 rows affected (0.00 sec) mysql > select database () # View current library +-+ | database () | +-+ | NULL | +-+ 1 row in set (0.00 sec) MongoDBuse winner2 # create winner library switched to db winner2show dbs # View all current libraries col 0.203125GBwinner2 0.203125GBdb # after deleting a current library in the current library winner2MySQL, check again that the current library is NULL, but after deleting the current library in MongoDB, it still displays the current library db.dropDatabase () # Delete the current library {"dropped": "winner2", "ok": 1} > db check the current library winner2show dbs# check all libraries col 0.203125GB >
2. Table and collection operations
After we have learned the relevant theoretical knowledge of the database, we all know that the data is stored in the table, and the database is used to store the data table. The table concept of MongoDB and MySQL is different. MongoDB stores the document data in the collection, while MySQL stores the data in the table (table). The collection has no table structure, and the table has related structures, such as fields, field types, indexes, primary keys, storage engines, and so on.
2.1 View all current tables
# MySQLmysql > use mysql Reading table information for completion of table and column namesYou can turn off this feature to get a quicker startup with-ADatabase changedmysql > show tables +-- + | Tables_in_mysql | +-+ | columns_priv | | db | | event | | func | | general_log | | help_category | | help_keyword | | help_relation | | help_topic | | innodb_index_stats | | innodb_table_stats | # MongoDBshow dbscol 0.203125GB > use colswitched to db col > show collectionssystem.indexeswinnerwinner2 >
2.2 create a table or collection
MySQL data is stored in related tables, while MongoDB data is stored in collections. MySQL supports plug-in storage engine, field type, index, primary key, and other reasons, which makes it more complex to create table structure statements. In application systems, performance optimization is closely related to table structure. MongoDB is mainly used to store data of type key (values), so it is much simpler.
Mysql > use winnerDatabase changedmysql > show tables-> Empty set (0.00 sec) mysql > create table winer (id int not null primary key auto_increment,-> name varchar (20) not null,-> age tinyint not null,-> sex tinyint not null default'0') engine=innodb charset utf8;Query OK, 0 rows affected (0.24 sec) mysql > desc winer +-+ | Field | Type | Null | Key | Default | Extra | + -+-+ | id | int (11) | NO | PRI | NULL | auto_increment | | name | varchar (20) | NO | | NULL | | age | tinyint (4) | NO | | NULL | | sex | tinyint (4) | NO | | 0 | | | +-+ # MongoDB creates a collection in MongoDB | To manipulate a collection, you do not need to create it first. You can insert data directly into the collection, and if the collection does not exist, the collection is automatically created and the data is inserted.
2.3 additions, deletions, modifications and queries of tables and collections
After knowing how to create a table, collection and other related knowledge, we have to think about how to modify the table or collection data, and the data stored in our application system and business system are mainly related operations such as additions, deletions, changes and queries.
2.3.1 insert data
Insert data into MySQL
Create a table SQL statement
CREATE TABLE `winer` (`id` int (11) NOT NULL AUTO_INCREMENT, `name` varchar (20) NOT NULL, `age` tinyint (4) NOT NULL, `sex` tinyint (4) NOT NULL DEFAULT '0mm, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 table structure mysql > desc winer-> +-+ | Field | Type | Null | Key | Default | Extra | + -+-+ | id | int (11) | NO | PRI | NULL | auto_increment | | name | varchar (20) | NO | | NULL | | age | tinyint (4) | NO | | NULL | | sex | tinyint (4) | NO | | 0 | | | +-+-+ 4 rows in set (0.00 sec) |
1. Insert a single piece of data
Mysql > insert into winer (name,age,sex) values ("MySQL", 20jue 1)->; Query OK, 1 row affected (0.09 sec) mysql > select * from winer +-+ | id | name | age | sex | +-+ | 1 | MySQL | 20 | 1 row in set (0.00 sec)
2. Batch insert
Mysql > insert into winer (name,age,sex) value ("MySQL", 20jue 1), ("Docker", 8 sec 0)->; Query OK, 2 rows affected (0.00 sec) Records: 2 Duplicates: 0 Warnings: 0mysql > insert into winer (name,age,sex) values ("MySQL", 20 Warnings 1), ("Docker", 8 Warnings 0)-> Query OK, 2 rows affected (0.01 sec) Records: 2 Duplicates: 0 Warnings: 0 difference between two insert statements value and values both can insert a single value or batch value mysql > select * from winer +-+ | id | name | age | sex | +-+ | 1 | MySQL | 20 | 1 | 2 | MySQL | 20 | 1 | 3 | Docker | 8 | 0 | 4 | MySQL | 20 | 1 | 5 | Docker | 8 | 0 | + -+ 5 rows in set (0.00 sec)
3. Other methods of inserting data
In MySQL, in addition to the traditional insert into insert data, we can also use load data mysqlimport and other ways to import data, or we can insert data from other tables into a table without detailed description.
2.3.2 insert data into MongoDB
MongoDB mainly stores document data, and the data structure of the document is basically the same as that of JSON. All data stored in the collection is in BSON format. BSON is a kind of json-like binary storage format, referred to as Binary JSON.
Insert document
MongoDB inserts a document into the collection using the insert () or save () method, with the following syntax:
Db.COLLECTION_NAME.insert (document) db.COLLECTION_NAME.save (document)
1. Simple insertion
Db.winner.find () # use find to view previous data in MongoDB before insertion, similar to select > db.winner.insert ({name: "linux"}) # insert result > db.winner.find () {"_ id": ObjectId ("592bf6bf1b8e279c43cbb021"), "name": "linux"} >
2. Define variables
> SQLNAME= ({"titile": "MongoDB learning practice", description: "MongoDB is a NoSQL database", by: "book learning"}) can define the data we want to insert as variables. Later, we use the method of loading variables to insert data > db.sql.insert (SQLNAME) > db.sql.find () {"_ id": ObjectId ("592bf8b5f3fed7ab45761fc1"), "titile": "MongoDB Learning practice", "description": "MongoDB is NoSQL Database", "by": "Book Learning"} >
3. For loop insertion
MongoDB also supports for (iSuppli select * from winer limit 10). +-+ | id | name | age | sex | +-+ | 1 | MySQL | 20 | 1 | 2 | MySQL | 20 | 1 | 3 | Docker | 8 | 0 | 4 | MySQL | 20 | 1 | 5 | Docker | 8 | 0 | 6 | MySQL | 20 | 1 | 1 | 7 | MySQL | 20 | 1 | 8 | Docker | 8 | 0 | 9 | MySQL | 20 | 1 | 10 | Docker | 8 | 0 | +-+ 10 rows in set (0.00 sec) use delete to delete all data mysql > delete from winer Query OK, 160rows affected (0.01sec) insert data mysql > insert into winer (name,age,sex) select name,age,sex from winner2;Query OK, 5 rows affected (0.01sec) Records: 5 Duplicates: 0 Warnings: check that the primary key of the data is indeed stored before the previous deletion, rather than starting over. Mysql > select * from winer +-+ | id | name | age | sex | +-+ | 249 | MySQL | 20 | 1 | 25 | MySQL | 20 | 1 | 25 | Docker | 8 | 0 | MySQL | 20 | 1 | | 253 | Docker | 8 | 0 | +-- -+ 5 rows in set (0.00 sec) truncate deletion check mysql > truncate winer Query OK, 0 rows affected (0.09 sec) mysql > insert into winer (name,age,sex) select name,age,sex from winner2;Query OK, 5 rows affected (0.01 sec) Records: 5 Duplicates: 0 Warnings: 0mysql > select * from winer +-+ | id | name | age | sex | +-+ | 1 | MySQL | 20 | 1 | 2 | MySQL | 20 | 1 | 3 | Docker | 8 | 0 | 4 | MySQL | 20 | 1 | 5 | Docker | 8 | 0 | + -- + 5 rows in set (0.00 sec) primary key starts at 1. Truncate releases the data pages used to store table data to delete the data, and only records the release of the pages in the transaction log
2. Delete data in MongoDB
The MongoDB remove () function is used to remove data from the collection. It is a good habit to execute the find () command before executing the remove () function to determine whether the condition is correct. Data deletion should be a very rigorous operation, not arbitrary operation, whether it is MySQL or MongoDB, or other databases, we should develop such a good habit. Strict conditions, backup, caution, etc.
The basic syntax format of the remove () method is as follows: db.collection.remove (,) MongoDB is later than version 2.6, and the syntax format is as follows: db.collection.remove (, {justOne:, writeConcern:}) parameter description: query: (optional) conditions for deleted documents. JustOne: (optional) if set to true or 1, only one document is deleted. WriteConcern: (optional) the level at which an exception is thrown deletes some data based on filter criteria > db.winner.find () db.winner.find () {"_ id": ObjectId ("592c2e01c070fc0df2f50f09"), "x": 0} {"_ id": ObjectId ("592c2e01c070fc0df2f50f0b"), "x": 2} {"_ id": ObjectId ("592c2e01c070fc0df2f50f0c"), "x": 3} {"_ id": ObjectId ("592c2e01c070fc0df2f50f0d") "x": 4} {"_ id": ObjectId ("592c2e01c070fc0df2f50f0e"), "x": 5} {"_ id": ObjectId ("592c2e01c070fc0df2f50f0f"), "x": 6} {"_ id": ObjectId ("592c2e01c070fc0df2f50f10"), "x": 7} {"_ id": ObjectId ("592c2e01c070fc0df2f50f11"), "x": 8} {"_ id": ObjectId ("592c2e01c070fc0df2f50f12") "x": 9} {"_ id": ObjectId ("592c2e01c070fc0df2f50f13"), "x": 10} {"_ id": ObjectId ("592c2e01c070fc0df2f50f14"), "x": 11} {"_ id": ObjectId ("592c2e01c070fc0df2f50f15"), "x": 12} {"_ id": ObjectId ("592c2e01c070fc0df2f50f16"), "x": 13} {"_ id": ObjectId ("592c2e01c070fc0df2f50f17") "x": 14} {"_ id": ObjectId ("592c2e01c070fc0df2f50f18"), "x": 15} {"_ id": ObjectId ("592c2e01c070fc0df2f50f19"), "x": 16} {"_ id": ObjectId ("592c2e01c070fc0df2f50f1a"), "x": 17} {"_ id": ObjectId ("592c2e01c070fc0df2f50f1b"), "x": 18} {"_ id": ObjectId ("592c2e01c070fc0df2f50f1c") "x": 19} {"_ id": ObjectId ("592c2e01c070fc0df2f50f1d"), "x": 20} Type "it" for more > db.winnerdb.winne.remove ({x 592c2e01c070fc0df2f50f1d 20}) > db.winedb.winne.find ({x 592c2e01c070fc0df2f50f1d 20}) delete all db.winner.remove () db.winner.find () show tables # check collections or use show collectionssystem.indexeswin_collectionwinerwinner because collections in MongoDB are not like tables and structures in MySQL, so when we delete all data, we can delete the entire collection directly, and a new collection will be created the next time we insert data. By comparison, db.winner.drop () > for (iDeposit I db.winner.drop () true > db.winner.find () > show tables;system.indexeswin_collectionwiner has deleted the previous collection, but such deletion will not affect the data we insert later. Delete a document definition variable SQLNAME= ({"titile": "MongoDB learning practice", description: "MongoDB is a NoSQL database", by: "book learning"}) in a duplicate document. Add data: > db.winner2.insert (SQLNAME) > db.winner2.find () # check all data {"_ id": ObjectId ("592c3628c1e073e087a335ee"), "titile": "MongoDB learning practice" "description": "MongoDB is NoSQL database", "by": "book learning"} {"_ id": ObjectId ("592c362ac1e073e087a335ef"), "titile": "MongoDB learning practice", "description": "MongoDB is NoSQL database", "by": "book learning"} {"_ id": ObjectId ("592c3639c1e073e087a335f0"), "titile": "MongoDB learning practice" "description": "MongoDB is the NoSQL database", "by": "Book Learning"} > execute delete db.winner2.remove ({"titile": "MongoDB Learning practice"}) check all the results again delete all db.winner2.find () > combine the previous syntax db.winner2.remove ({"titile": "MongoDB Learning practice") 1) only part of db.winner2.find () {"_ id": ObjectId ("592c391b30de16129bcc9310"), "titile": "MongoDB learning practice", "description": "MongoDB is NoSQL database", "by": "book learning"} {"_ id": ObjectId ("592c391c30de16129bcc9311"), "titile": "MongoDB learning practice", "description": "MongoDB is NoSQL database" are deleted. "by": "Book Learning"}
2.3.4 change data
Changing data in MySQL is mainly realized by statements such as update table set where. Do a simple example without describing it in detail.
Mysql > select * from winner2 +-+ | id | name | age | sex | +-+ | 1 | MySQL | 20 | 1 | 2 | MySQL | 20 | 1 | 3 | Docker | 8 | 0 | 4 | MySQL | 20 | 1 | 5 | Docker | 8 | 0 | + -- + 5 rows in set (0.00 sec) mysql > update winner2 set name= "MySQLDBA" where id=2 # change name with id 2 to MySQLDBAQuery OK, 1 row affected (0.03 sec) Rows matched: 1 Changed: 1 Warnings: 0mysql > select * from winner2 +-+ | id | name | age | sex | +-- + | 1 | MySQL | 20 | 1 | 2 | MySQLDBA | 20 | 1 | 3 | Docker | 8 | 0 | 4 | MySQL | 20 | 1 | 5 | Docker | 8 | 0 | +- -+ 5 rows in set (0.00 sec)
Data changes in MongoDB are also implemented through update () and save (), and it is important to note that update () changes a document record that fits the condition by default.
Update () and save ()
The update () method is used to update existing documents. The syntax format is as follows:
Db.collection.update (, {upsert:, multi:, writeConcern:})
Parameter description:
Query: the query condition of update, similar to that after where in a sql update query.
Update: the object of update and some updated operators (such as $, $inc...), etc., can also be understood as after set in the sql update query
Upsert: optional, this parameter means that if there is no record of update, whether to insert objNew,true is insert, default is false, do not insert.
Multi: optional. Mongodb defaults to false. Only the first record found is updated. If this parameter is true, multiple records are checked out according to the condition and all of them are updated.
WriteConcern: optional, the level at which the exception is thrown.
Save () method
The save () method replaces an existing document with an incoming document. The syntax format is as follows: db.collection.save (, {writeConcern:})
Parameter description:
Document: document data.
WriteConcern: optional, the level at which the exception is thrown.
More Instanc
Update only the first record:
Db.col.update ({"count": {$gt: 1}}, {$set: {"test2": "OK"}}); all updates: db.col.update ({"count": {$gt: 3}}, {$set: {"test2": "OK"}}, false,true) Only add the first entry: db.col.update ({"count": {$gt: 4}}, {$set: {"test5": "OK"}, true,false); add all: db.col.update ({"count": {$gt: 5}}, {$set: {"test5": "OK"}}, true,true) Update all: db.col.update ({"count": {$gt: 15}}, {$inc: {"count": 1}}, false,true); update only the first record: db.col.update ({"count": {$gt: 10}}, {$inc: {"count": 1}}, false,false)
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.