SpringBoot e-commerce project mall (30k+star) address: https://github.com/macrozheng/mall
abstract
Although relational databases are still the mainstream now, it is necessary to learn a mainstream NOSQL database to supplement them when facing some requirements.MongoDB is a rich NoSQL database. This introductory tutorial is organized from its most commonly used parts and is expected to be helpful.
brief introduction
MongoDB is a database based on distributed file storage.Written in C++, it is designed to provide scalable high performance data storage solutions for WEB applications.MongoDB is a product between relational and non-relational databases and is the most versatile and similar to relational databases among non-relational databases.
install
The previous MongoDB installation tutorial was based on version 3.2 and found that some friends had problems installing it with the new version. This time we will install it again with the latest version. The version of MongoDB used in this article is 4.2.5. Overall, the installation of the new version is simpler.
Installation under Windows
- Download the MongoDB installation package, select Windows x64 version installation, download address: https://www.mongodb.com/downl...
- Run the MongoDB installation package and select a custom installation to set the installation path.
- Configure MongoDB to run as a service and configure data and log directories;
- Cancel the installation option of MongoDB Compass (it is very slow to do so) and install it yourself.
- double-clickMongo.exeMongoDB can run its own client to operate MongoDB;
- The following information will be displayed when the connection is successful;
- If you need to remove the MongoDB service, simply run the cmd tool with administrator privileges and enter the following command.
sc.exe delete MongoDB
Installation under Linux
- Download the Docker image of MongoDB;
docker pull mongo:4.2.5
- Start the MongoDB service using the Docker command;
docker run -p 27017:27017 --name mongo \ -v /mydata/mongo/db:/data/db \ -d mongo:4.2.5
- Sometimes we need to set up an account for MongoDB, which can be started with the following command;
docker run -p 27017:27017 --name mongo \ -v /mydata/mongo/db:/data/db \ -d mongo:4.2.5 --auth
- Then we need to enter the MongoDB client in the container;
docker exec -it mongo mongo
- An account is then created in the admin collection to connect, where a root-based super administrator account is created;
use admin db.createUser({ user: 'mongoadmin', pwd: 'secret', roles: [ { role: "root", db: "admin" } ] });
- Verify that you can log in when the creation is complete;
db.auth("mongoadmin","secret")
- The entire account creation process can be referred to in the following figure.
Client Tools
There are many client tools for MongoDB, including MongoDB Compass, which is not installed on MongoDB, and Navicat version 15 also has management capabilities for MongoDB.Here we are using a free client tool, Robo 3T (formerly Robomongo).
- First download the client tool, download the address: https://robomongo.org/download
- Unzip after downloading, and double-click robo3t.exe to use;
- Then create a connection to MongoDB;
- Once the connection has been successfully created, you can operate on MongoDB.
Related concepts
MongoDB is most like a relational database among non-relational databases, so we'll look at its concept by comparing it to a relational database.
SQL concepts MongoDB concepts Explanation/Explanation database database data base table collection Database tables/collections row document Data Record Row/Document column field Data Fields/Fields index index Indexes primary key primary key Primary key, MongoDB will automatically _id field set as primary keyDatabase Operation
- Create the database, use the use command to create the database, when the first data is inserted, create the database, for example, create a test database;
> use test switched to db test > db.article.insert() WriteResult({ "nInserted" : 1 }) > show dbs admin 0.000GB config 0.000GB local 0.000GB test 0.000GB
- Delete the database, using the dropDatabase() method in the db object to delete;
> db.dropDatabase() { "dropped" : "test", "ok" : 1 } > show dbs admin 0.000GB config 0.000GB local 0.000GB
Collection Operation
- Create a collection by using the createCollection() method in the db object, such as creating an article collection;
> use test switched to db test > db.createCollection("article") { "ok" : 1 } > show collections article
- Delete a collection by using the drop() method of the collection object, such as deleting an article collection;
> db.article.drop() true > show collections
Document operation
The above database and collection operations are done on the client side of MongoDB, and the following document operations are done on Robomongo.
Insert Document
- MongoDB inserts a document into the collection through the insert() method of the collection object with the following syntax;
db.collection.insert(document)
- Insert a document using the insert() method of the collection object, such as inserting an article document;
db.article.insert()
- Documents can be obtained by using the find() method of the collection object, such as getting all the article documents;
db.article.find({})
{ "_id" : ObjectId("5e9943661379a112845e4056"), "title" : "MongoDB Course", "description" : "MongoDB Is a Nosql data base", "by" : "Andy", "url" : "https://www.mongodb.com/", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100.0 }
Update Document
- MongoDB updates documents in a collection by updating () the collection object with the following syntax;
db.collection.update( <query>, <update>, { multi: <boolean> } ) # Query: Modified query condition, similar to WHERE part in SQL # Update: Operator to update attributes, similar to the SET section in SQL # multi: When set to true, all eligible documents are updated, defaulting to false updating only the first found item
- Modify the titles of all documents whose titles are MongoDB tutorials to MongoDB;
db.article.update({'title':'MongoDB Course'},{$set:{'title':'MongoDB'}},)
- In addition to the update() method, the save() method can be used to replace an existing document with the following syntax;
db.collection.save(document)
- This time we will change the title of the document whose ObjectId is 5e9943661379a112845e4056 to the MongoDB tutorial.
db.article.save({ "_id" : ObjectId("5e9943661379a112845e4056"), "title" : "MongoDB Course", "description" : "MongoDB Is a Nosql data base", "by" : "Andy", "url" : "https://www.mongodb.com/", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100.0 })
remove document
- MongoDB deletes documents in a collection by removing () the collection object with the following syntax;
db.collection.remove( <query>, { justOne: <boolean> } ) # Query: Deleted query condition, similar to WHERE part in SQL # justOne: set to true to delete only one record, default to false to delete all records
- Delete all documents title d for the MongoDB tutorial;
db.article.remove({'title':'MongoDB Course'})
consult your documentation
- MongoDB queries the document through the find() method of the collection object with the following syntax;
db.collection.find(query, projection) # query: query criteria, similar to WHERE parts in SQL # Projection: Optional, use the projection operator to specify the returned key
- Query all documents in the article collection;
db.article.find()
/* 1 */ { "_id" : ObjectId("5e994dcb1379a112845e4057"), "title" : "MongoDB Course", "description" : "MongoDB Is a Nosql data base", "by" : "Andy", "url" : "https://www.mongodb.com/", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 50.0 } /* 2 */ { "_id" : ObjectId("5e994df51379a112845e4058"), "title" : "Elasticsearch Course", "description" : "Elasticsearch Is a search engine", "by" : "Ruby", "url" : "https://www.elastic.co/cn/", "tags" : [ "elasticearch", "database", "NoSQL" ], "likes" : 100.0 } /* 3 */ { "_id" : ObjectId("5e994e111379a112845e4059"), "title" : "Redis Course", "description" : "Redis Is a key-value data base", "by" : "Andy", "url" : "https://redis.io/", "tags" : [ "redis", "database", "NoSQL" ], "likes" : 150.0 }
- The conditional operators in MongoDB are explained by comparing them with SQL statements.
- Conditional queries that query all documents title d for the MongoDB tutorial;
db.article.find({'title':'MongoDB Course'})
- Conditional query, query all documents with likes greater than 50;
db.article.find({'likes':{$gt:50}})
- The AND condition can be achieved by passing in multiple keys in the find() method, separated by commas, such as querying all documents with title as MongoDB tutorial and by as Andy;
db.article.find({'title':'MongoDB Course','by':'Andy'})
- The OR condition can be achieved by using the $or operator, such as querying all documents title d for Redis or MongoDB tutorials;
db.article.find({$or:[{"title":"Redis Course"},{"title": "MongoDB Course"}]})
- A combination of AND and OR conditions, such as querying documents with likes greater than 50 and title s for Redis or MongoDB tutorials.
db.article.find({"likes": {$gt:50}, $or: [{"title": "Redis Course"},{"title": "MongoDB Course"}]})
Other operations
Limit and Skip operations
- To read a specified number of documents, you can use the limit() method with the following syntax;
db.collection.find().limit(NUMBER)
- Query only two pieces of data in the article collection;
db.article.find().limit(2)
- Skip a specified number of documents to read, using the skip() method with the following syntax;
db.collection.find().limit(NUMBER).skip(NUMBER)
- Starting with Article 2, query two pieces of data in the article collection;
db.article.find().limit(2).skip(1)
sort
- The sort() method is used in MonoDB to sort the data. The sort() method specifies the sorting field by parameters, and uses 1 and -1 to specify the sorting method, with 1 in ascending order and -1 in descending order.
db.collection.find().sort()
- Sort documents in descending order by the likes field of the document in the article collection;
db.article.find().sort()
Indexes
- Indexes can often greatly improve query efficiency, and without indexes, MongoDB must scan each file in the collection and select those records that meet the query criteria when reading data.
- MongoDB uses the createIndex() method to create an index with the following syntax;
db.collection.createIndex(keys, options) # Background: the indexing process will block other database operations, set to true for background creation, default to false # Unique: set to true to create a unique index # Name: Specifies the index name, if not specified it will be automatically generated
- Create indexes for title and description fields, 1 for ascending index and -1 for descending index, specifying background creation;
db.article.createIndex({"title":1,"description":-1}, )
- View indexes that have been created in the article collection;
db.article.getIndexes()
/* 1 */ [ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.article" }, { "v" : 2, "key" : { "title" : 1.0, "description" : -1.0 }, "name" : "title_1_description_-1", "ns" : "test.article", "background" : true } ]
polymerization
- Aggregation in MongoDB uses the aggregate() method, similar to the group by statement in SQL, with the following syntax;
db.collection.aggregate(AGGREGATE_OPERATION)
- Common operators in aggregation are as follows;
- Aggregate documents based on the by field and calculate the number of documents, similar to the count() function in SQL;
db.article.aggregate([{$group : }}])
/* 1 */ { "_id" : "Andy", "sum_count" : 2.0 } /* 2 */ { "_id" : "Ruby", "sum_count" : 1.0 }
- Aggregate documents based on by fields and calculate the average value of likes fields, similar to avg() statements in SQL;
db.article.aggregate([{$group : }}])
/* 1 */ { "_id" : "Andy", "avg_likes" : 100.0 } /* 2 */ { "_id" : "Ruby", "avg_likes" : 100.0 }
regular expression
- MongoDB uses the $regex operator to set regular expressions that match strings and can be used to fuzzy queries, similar to like operations in SQL;
- For example, query the document containing the tutorial in the title;
db.article.find(})
- Case-insensitive fuzzy queries, using the $options operator;
db.article.find(})
Use with SpringBoot
Specific reference: "mall Integrates Mongodb for Document Operations"
Public Number
mall project In the full series of learning tutorials, focus on the first time public number is available.