MongoDB is a NoSQL database, this paper mainly introduces some basic concepts and operations in MongoDB, as well as the installation and use of visual tools.
Author: Passionate Latiao girl reading time about 20 minutes +
1 introduction of directing
MongoDB is a NoSQL database that stores data objects consisting of key-value pairs. All data stored in MongoDB collections is in BSON format. BSON is a jSON-like storage format, short for Binary JSON. As follows:
{
"_id" : ObjectId("5c89f787ca6e4e3ac1ecabkk"),
"_plat" : "test_plat0"."update_time" : ISODate("The 2019-06-03 T15:00:42. 142 z"),
"create_time" : ISODate("The 2019-03-14 T14: I. 217 z"),
"creator" : "test_user"."admin" : [
"admin1"."admin2"]."ops" : [
"ops1"]."labels" : {
"department" : "departmentA"."main_class" : "mainClassA"}}Copy the code
The following introduces some basic concepts of MongoDB in relation to relational databases:
Relational database terminology | Directing a term | instructions |
---|---|---|
database | database | The database |
table | collection | Database tables/collections |
row | document | Record line/document |
column | field | Data fields/fields |
index | index | The index |
primary key | primary key | Primary key. Mongodb automatically sets the _ID field as the primary key |
To better understand MongoDB, consider the following comparison:
id | The name | age | gender |
---|---|---|---|
1 | Zhang SAN | 23 | male |
2 | Li si | 21 | male |
The data form of the above relational data in MongoDB is:
{
"_id" : ObjectId("5c89f787ca6e4e3ac1ehhb23"),
"Name" : "Zhang"."Age": 23."Gender" : "Male"
}
{
"_id" : ObjectId("5c89f787ca6e4e3ac1ehhb24"),
"Name" : "Bill"."Age": 21."Gender" : "Male"
}
Copy the code
2 Basic MongoDB operations
This topic describes how to operate MongoDB on the CLI. The following uses MongoDB installed on CentOS as an example.
2.1 Db, set and other basic operations
DB view, create, delete, set view, create, delete and other operations are as follows:
[root] mongo Enter mongo to enter the MongoDB command interaction mode
> show dbs List the existing db
> use my_db If my_db exists, switch to my_db, if not, create my_db
> db Display the current DB
> show dbs # my_db is not found in the list, because there is no actual data or collection in db
> db.createCollection("my_col") Create my_col
> db.my_col_new.insert({"name":"Test it out."}) # insert a column of data into my_col_new. If the column does not exist, it will be created automatically
> show collections List all sets below db
> show tables # Show Collections
> db.my_col.drop() # delete collection my_col
> db.dropDatabase() # delete the current database, before executing the db command to confirm that the current database is the one you want to delete
Copy the code
2.2 Data Insertion
There are four methods to insert data: INSERT, insertOne, insertMany, and save. The following are detailed examples.
> db.my_col.insert({"name":"xiaoming"}) Insert allows you to insert a single piece of data
> db.my_col.insert([{"name":"xiaoming"}, {"name":"test_user"}]) Insert can also be used to insert multiple pieces of data
> db.my_col.insertOne({"name":"xiaoming"}) #insertOne can only insertOne data
> db.my_col.insertMany([{"name":"xiaoming"}]) #insertMany can insert one or more pieces of data, but the data must be organized as a list
> db.my_col.save([{"name":"xiaoming"}, {"name":"test_user"}]) # If the _id is not specified, save functions as insert
> db.my_col.save({"_id":ObjectId("5d07461141623d5db6cd4d43"),"name":"xiaoming"}) If you specify an id, mongodb will not automatically generate an id for this record. Only save can specify an id. Insert, insertOne, and insertMany cannot specify an id
Copy the code
2.3 Data Modification
There are two methods for modifying data: Update and Save.
2.3.1 the update
First, take a look at the syntax of the update. Pay special attention to the values of some optional parameters that will directly affect the result of your update:
db.collection.update(
<query>, SQL > select * from 'where'
<update>, #update objects and some update operators, etc., can also be understood after the SQL update statement set
{
upsert: <boolean>, Insert objNew if no update record exists. True inserts objNew. Default is false, no inserts
multi: <boolean>, If this parameter is true, mongodb will update all of the records found by the criteria
writeConcern: <document> Optional, the level of exception to be thrown})Copy the code
Suppose you have a table of student grades:
> db.my_col.insert([{"name":"xiaoming"."class":"c++"."score": 60}, {"name":"xiaoming"."class":"python"."score":95}])
> db.my_col.find().pretty()
{
"_id" : ObjectId("5d0751ef41623d5db6cd4d44"),
"name" : "xiaoming"."class" : "c++"."score": 60} {"_id" : ObjectId("5d0751ef41623d5db6cd4d46"),
"name" : "xiaoming"."class" : "python"."score": 95}Copy the code
Xiaoming: my c++ course grade is wrong. I need to change it to 75.
> db.my_col.update({"_id":ObjectId("5d0751ef41623d5db6cd4d44")}, {$set: {"score": 75}})Copy the code
Xiaoming’s name is wrong and needs to be corrected.
> db.my_col.update({"name":"xiaoming"}, {$set: {"name":"xming"}}) Only one record will be modified
> db.my_col.update({"name":"xiaoming"}, {$set: {"name":"xming"}},{multi:true}) # That's right
Copy the code
Change xming’s Java course score to 95, and insert a record if it cannot be found
> db.my_col.update({"name":"xming"."class": "java"}, {$set: {"score": 95}}.true)
Copy the code
2.3.2 save
The save method replaces the existing document with the incoming document. The syntax is as follows:
db.collection.save(
<document>, # Document data
{
writeConcern: <document> Optional, the level of exception to be thrown})Copy the code
Take, for example, the student achievement chart above:
> db.my_col.save({
"_id" : ObjectId("5d0751ef41623d5db6cd4d44"), If the _id is specified, the new document will overwrite the old document
"name" : "xming"."class" : "c++"."score": 80})Copy the code
2.4 Data Deletion
You can use deleteOne, deleteMany, and remove to delete data.
Against 2.4.1 deleteOne and deleteMany
The usage method is as follows:
> db.my_col.deleteOne({"name":"xming"}) # delete a score from xming
> db.my_col.deleteMany({"name":"xming"}) # delete all grades from xming
> db.my_col.deleteMany({}) Delete all the content in the transcript
Copy the code
Remove 2.4.2
Let’s start with the syntax:
db.collection.remove(
<query>, This parameter is optional
{
justOne: <boolean>, Set this parameter to true or 1 to delete only one document. Set this parameter to false to delete all matching documents
writeConcern: <document> Optional, the level of exception to be thrown})Copy the code
Delete all grades from xming:
> db.col.remove({"name":"xming"})
> db.repairDatabase() The #remove method does not actually free up space, and you need to continue executing the DB.RepairDatabase () to reclaim disk space
> db.runCommand({ repairDatabase: 1 }) # execute the same sentence as before
Copy the code
Ps: remove is now obsolete and is now officially recommended to use deleteOne and deleteMany methods.
2.5 Data Query
Data query methods include findOne and find. The two methods use the same parameters, but findOne returns only one matched data, and find returns all matched data. The following describes the use of find.
2.5.1 Conditional operators
operation | SQL query writing method | Mongo query writing method |
---|---|---|
Is equal to the | select * from my_col where score = 75; | db.my_col.find({“score”: 75}).pretty() |
Less than | select * from my_col where score < 75; | db.my_col.find({“score”: {$lt: 75}}).pretty() |
Less than or equal to | select * from my_col where score <= 75; | db.my_col.find({“score”: {$lte: 75}}).pretty() |
Is greater than | select * from my_col where score > 75; | db.my_col.find({“score”: {$gt: 75}}).pretty() |
Greater than or equal to | select * from my_col where score >= 75; | db.my_col.find({“score”: {$gte: 75}}).pretty() |
Is not equal to | select * from my_col where score ! = 75; | db.my_col.find({“score”: {$ne: 75}}).pretty() |
Ps: Pretty allows query results to be printed as formatted JSON for easy viewing
2.5.2 Sorting, limit, and skip
Show students’ c++ course scores in descending order, only show students in 10th to 20th place:
> db.my_col.find({"class": "c++"}).sort({"score": -1}).skip(9).limit(11).pretty()
#sort: 1 is in ascending order, -1 is in descending order, default ascending order
#limit: How many pieces of data to display
#skip: How many pieces of data to skip
Copy the code
2.5.3 Querying AND and or of Compound Conditions
And: The find method can pass in multiple key-value pairs separated by commas, the and condition of regular SQL
Select c++ from xiaoming
> db.my_col.find({"name": "xiaoming"."class": "c++"}).pretty()
Copy the code
Query for scores between 75 and 85:
> db.my_col.find({"score": {$gt: 75, $lt: 85}}).pretty()
Copy the code
Or: MongoDB or conditional statement uses keyword $or, syntax format is as follows:
> db.col.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()
Copy the code
Select * from xiaoming; select * from Zhangsan;
> db.my_col.find({$or: [{"name": "xiaoming"}, {"name": "zhangsan"}]}).pretty()
Copy the code
And + or;
Select * from c++ where xiaoming is running
> db.my_col.find({"name": "xiaoming".$or: [{"class": "c++"}, {"class": "python"}]}).pretty()
Copy the code
2.5.4 Including IN, Excluding NIN, and All
Select * from xiaoming, Zhangsan and Lisa where id = 0;
> db.my_col.find({"name": {$in: ["xiaoming"."zhangsan"."lisa"]}}).pretty()
Copy the code
Select * from xiaoming, Zhangsan and Lisa where username = “xiaoming”;
> db.my_col.find({"name": {$nin: ["xiaoming"."zhangsan"."lisa"]}}).pretty()
Copy the code
In and nin are easy to understand, similar to SQL. All is similar to in, except that in only needs to satisfy one value in the list, while all needs to satisfy all values in the list. For example, there is a schedule showing the courses taken by each student:
> db.course.find().pretty()
{
"_id" : ObjectId("5d084f1541623d5db6cd4d4c"),
"name" : "xiaoming"."course" : [
"c++"."python"."java"]} {"_id" : ObjectId("5d084f1c41623d5db6cd4d4d"),
"name" : "lisa"."course" : [
"c++"."python"."java"]} {"_id" : ObjectId("5d084f4a41623d5db6cd4d4e"),
"name" : "tom"."course" : [
"c++"."python"]}Copy the code
Need to find students who have taken c++ and Java courses:
> db.course.find({"course": {$all: ["c++"."java"]}}).pretty() Use the all operator to indicate that both c++ and Java are required
Copy the code
2.5.5 Checking whether a Field exists
For example, here is a table representing student information:
> db.stu_info.find().pretty()
{
"_id" : ObjectId("5d08519a41623d5db6cd4d4f"),
"name" : "xiaoming"."tel" : "138xxxxxxxx"
}
{
"_id" : ObjectId("5d08531641623d5db6cd4d50"),
"name" : "lisa"
}
{
"_id" : ObjectId("5d08542e41623d5db6cd4d51"),
"name" : "tom"."tel" : null
}
Copy the code
Need to find students without TEL field:
> db.stu_info.find({"tel": {$exists: false}}).pretty() If the # field does not exist, use false; if it does exist, use true
Copy the code
2.5.6 Null Processing NULL
Use the student information table above as an example to find the student whose TEL is null:
> db.stu_info.find({"tel": null}).pretty()
{
"_id" : ObjectId("5d08531641623d5db6cd4d50"),
"name" : "lisa"
}
{
"_id" : ObjectId("5d08542e41623d5db6cd4d51"),
"name" : "tom"."tel" : null
}
Copy the code
Null tel = null tel = null If only tel is null:
> db.stu_info.find({"tel": {$in:[null], $exists:true}}).pretty()
Copy the code
2.5.7 Modulus operation mod
For example, find data where a student’s grade is modulo 10 = 0 (i.e. 100, 90, 80… And so on) :
> db.my_col.find({"score": {$mod: [10, 0]}}).pretty()
Copy the code
2.5.8 RegeX matches matches
Select * from student where name starts with a;
> db.my_col.find({"name": {$regex: /^a.*/}})
Copy the code
2.5.9 Obtaining count of the Query results
The number of items to obtain the student’s transcript:
> db.my_col.find().count()
Copy the code
When the limit method is used to limit the number of records returned, the count method still returns the total number of records by default. If you want to return the number of records after the limit, use either count(true) or count(non-0) :
> db.my_col.find().count()
4
> db.my_col.find().limit(1).count()
4
> db.my_col.find().limit(1).count(true1)Copy the code
2.5.10 distinct
Query the list of all students in the course grade table:
> db.my_col.distinct("name")
Copy the code
2.6 the aggregation aggregate
In MongoDB, the aggregation framework can be used to transform and combine the documents in the collection and complete some complex query operations. The aggregation framework creates a pipeline of artifacts for processing a series of documents. These components include but are not limited to:
The operator | meaning |
---|---|
$match | screening |
$project | Cast, select the desired field or rename the field |
$group | grouping |
$unwind | Break up |
$sort | The sorting |
$limit | Limit the number of query entries |
$skip | I’m going to skip some numbers |
When we need more than one operator to aggregate documents, we can pass in an array condition, which is also a common use of aggregate:
> db.my_col.aggregate([
{$match: {"name": "xiaoming"}}, # Find xiaoming's course grades
{$project: {"_id": 0}}, # do not need the _id field
{$sort: {"score": 1,"class": 1}}, # sort by descending score; Students with the same score will be sorted in ascending order by course name
{$skip: 1}.# Skip a piece of data
{$limit: 1} Display only one piece of data
])
Copy the code
$match is used to filter the set of documents, which can then be aggregated on the filtered subset of documents. $match” can use all the normal query operators (“$gt”, “$lt”, “$in”, etc.). In general, in practice, “$match” should be placed at the front of the pipe whenever possible. This has two advantages: it can quickly filter out unwanted documents to reduce the workload of the pipeline; Second, if “$match” is executed before projection and grouping, the query can use the index.
$project can extract fields from subdocuments, which can be renamed. Student_name = student_name; student_name = student_name; student_name = student_name;
> db.my_col.aggregate([
{$project: {"_id": 0."student_name": "$name"."core": 1, "class": 1}}])Copy the code
$sort $skip $limit
$group is similar to group BY in SQL, mainly used for data processing, for example, calculate the total course score of each student:
> db.my_col.aggregate([
{$group: {_id: "$name", total: {$sum: "$score"}}}])Copy the code
$sum = $avg; $min = $Max;
$unwind splits each value in the array into a separate document, such as the following entry for a blog post and the following comment:
> db.blog.findOne().pretty()
{
"_id":ObjectId("5359f6f6ec7452081a7873d7"),
"title":"This is a blog."."auth":"xiaoming"."comments":[
{
"author":"lisa"."date":ISODate("The 2019-01-01 T17:52:04. 148 z"),
"text":"Nice post"
},
{
"author":"tom"."date":ISODate("The 2019-01-01 T17:52:04. 148 z"),
"text":"I agree"}}]Copy the code
Now to find Lisa’s comments, split each comment into a separate document using $unwind and then perform a match query:
> db.blog.aggregate({"$unwind":"$comments"{})"results":
{
"_id":ObjectId("5359f6f6ec7452081a7873d7"),
"title":"This is a blog."."author":"xiaoming"."comments": {"author":"lisa"."date":ISODate("The 2019-01-01 T17:52:04. 148 z"),
"text":"Nice post"}}, {"_id":ObjectId("5359f6f6ec7452081a7873d7"),
"title":"This is a blog."."author":"xiaoming"."comments": {"author":"tom"."date":ISODate("The 2019-01-01 T17:52:04. 148 z"),
"text":"I agree"
}
}
}
> db.blog.aggregate([
{"$unwind":"$comments"},
{"$match": {"comments.author":"lisa"}}])Copy the code
2.7 the index
Indexes can greatly improve query efficiency. If there is no index, MongoDB must scan every file in the collection and select the records that meet the query conditions when reading data. The query efficiency of scanning the whole collection is very low, especially when dealing with a large amount of data, the query can take tens of seconds or even a few minutes, which is very fatal to the performance of the website. An index is a special data structure that is stored in a collection of data that is easy to traverse and read. An index is a structure that sorts the values of one or more columns in a database table.
The basic syntax for creating an index is as follows:
db.collection.createIndex(
{key1: option1, key2: option2}, #key (1); option (-1)
{
background: <boolean>, If the background value is set to true, the index can be created in the background. The default value is false
unique: <boolean> # Optional whether the index created is unique. Specifies true to create a unique index. The default value is false
name: <string> The name of the index is optional. If not specified, MongoDB generates an index name from the join index's field name and sort order
sparse: <boolean> # optional, disable index for field data that does not exist in the document; Note that if this parameter is set to true, documents that do not contain the corresponding field will not be queried in the index field. The default value is false})Copy the code
Create index for student score table:
> db.my_col.createIndex({"score": 1}, {background: true}) # create in the background
> db.my_col.getIndexes() Check the collection index
> db.my_col.totalIndexSize() Check the set index size
> db.my_col.dropIndex("Index name") Drop set index
> db.my_col.dropIndexes() Drop all indexes in the set
Copy the code
3 Visualization Tools
MongoDB has a cross-platform visualization tool called Robo 3T that is very simple and easy to use.
Download and install it at robomongo.org/download
After the download and installation is successful, click File → Connect to pop up the following small window, and then click Create to create a new configuration:
Fill in the correct address and port and save.
If you are unable to connect to MongoDB after installing the DB server, it may be because the DB server is configured to listen on 127.0.0.1 and needs to change to 0.0.0.0.
Double-click the configured connection to enter the interactive interface, as shown below. The left side is the database and collection information, and the right side is the query result. You can enter query commands on the cli and click Execute to perform filtering operations.
You can also directly right-click the document to view, edit and other operations, very convenient.
4 Reference Documents
Directing a novice tutorial: www.runoob.com/mongodb/mon…
Mongo advanced query: cw.hubwiz.com/card/c/543b…
Mongo aggregation: cw.hubwiz.com/card/c/5481…
Directing the official document: docs.mongodb.com/manual/intr…
Robo 3 t use tutorial: www.cnblogs.com/tugenhua070… > MongoDB is a NoSQL database. This article mainly introduces some basic concepts and operations in MongoDB, as well as the installation and use of visual tools.
Pay attention to [IVWEB community] public number to get the latest weekly articles, leading to the top of life!