MongoDB
Article directory
1. Basic introduction
concept
MongoDB is a non-relational database that stores JSON documents. The structure is as follows:
There are many collections in one database, and many documents in one collection.
run
Run MongoDB with Docker:
docker run --name mymongo -v /mymongo/data:/data/db -d mongo
# --name给容器起别名
MongoDB uses port 27017 by default
View logs
docker logs 容器名称
Mongo Shell
Mongo Shell is a JS client for manipulating MongoDB
# 运行Mongo Shell
docker exec -it 容器名称 mongo
2. Add, delete, modify and check operations
Each document stored in MongoDB has a unique id, called the document primary key, stored in the _id
field :
- The primary key is unique (the primary keys of different documents cannot be repeated), and supports all data types except arrays. One document can be used as the primary key of another document, which is called a composite primary key.
- If no primary key is specified when the document is created, an object primary key is created by default
ObjectId("包含创建时间的字串")
.- Extract the creation time of the object's primary key:
ObjectId("xxx").getTimestamp()
- Extract the creation time of the object's primary key:
2.1 Creating documents
- use
db.集合.insert()
ordb.集合.save()
command- The insert command is further divided into insertOne, insertMany, insert
Basic syntax:
db.<collection>.insertOne(
<document>,
{
writeConcern: <document>
}
)
<collection>
To be replaced with the collection where the document is stored, this collection will be created automatically if it does not exist<document>
to be replaced with the written document itselfwriteConcern: <document>
Defines the security write level of this document creation operation- The safe write level is used to determine whether a database write operation is successful or not.
- The higher the secure write level, the lower the risk of losing data, but the higher the latency of the write operation
- If you do not specify a secure write level, MongoDB will use the default level
- Note: The safe write level and the JSON key-value pair of the document are not in a brace, you need to write another brace
Demo:
Run Mongo Shell
docker exec -it 容器名称 mongo
use test database
use test
# 数据库存在则切换到该数据库,数据库不存在则自动创建该数据库并切换到该数据库
View all collections of the test database
show collections
# 现在新创建的test数据库中还没有集合
Write the document to the accounts collection
db.accounts.insertOne(
{
_id: "account1",
name: "alice",
balance: 100
}
)
Primary key specified, but no secure write level specified
operation result
{
"acknowledged" : true, "insertedId" : "account1" }
"acknowledged" : true
Indicates that the secure write level is enabled, and the status of the default secure write level is displayed at this time."insertedId" : "account1"
Shows the primary key of the document being written to
If insertOne encounters an error
Create a new document with a duplicate primary key id:
An error occurred:
Exceptions can be caught:
The exception message printed by the library function print is more intuitive:
Automatically generate primary key id
Just omit the _id
field :
Create multiple documents
Basic syntax:
- The ordered parameter is used to decide whether to write these documents in order, the value is true or false, the default value is true
- If the value of ordered is false, MongoDB can shuffle the order of the documents and speed up the writing
Example:
If insertMany encounters an error
- When writing sequentially, once an error is encountered, the remaining documents, whether correct or not, will not be executed
- When writing out of order, even if some documents cause errors, the remaining correct documents are still written
Create multiple or single documents
Basic syntax:
Example:
save command
Basic syntax:
- When the save instruction processes a new document, the insert instruction is called
composite primary key
- The composite primary key must also satisfy uniqueness, otherwise an error will be reported
- The content in the composite primary key is the same but the order of the key-value pairs is different, and the primary key is not considered to be duplicated
2.2 Reading documents
Basic syntax:
db.集合.find(<query>, <projection>)
query
Indicates the query condition in JSON format (optional), if it is empty, it means there is no query condition, that is, all documents are queriedprojection
Represents a projection operation on the result (optional)- You can return some fields of the document to improve efficiency (note that it is not returning part of the document)
- If the projected field is omitted, all documents that qualify for the full field are returned
- Whether projection is used or not, the number of query results is the same, but using projection will cause the returned document not to display all fields
2.2.1 Read all documents
db.集合.find()
Display documents more intuitively:db.集合.find().pretty()
2.2.2 Matching query
2.2.3 Comparison Operators
** Note: **Originally, the query condition is that the key-value share a curly bracket, but now the comparator and the value need another curly bracket.
Example 1:
Note:$ne
Documents that do not contain the query field will be queried. It can be understood that it is not equal to not containing the query field.
Example 2:
Comparison operators can also compare lexicographically:
Example 3:
Notice:
- The value corresponding to the in and nin operators should be placed in an array
- nin filters out documents that do not contain the query field
Example 4:
in is used in conjunction with regular expressions:
2.2.4 Logical Operators
** Note: **Using logical operators requires an additional layer of curly braces.
Example 1:
** Note: **not will also filter out documents that do not contain the query field.
Example 2:
Simplified writing 1 (used on different fields):
Simplified writing 2 (used on the same field):
Example 3:
** Note: **nor filters out documents that do not contain the query field.
2.2.5 Field Operators
$exists
: matches if there is a document with the specified field
$type
: matches documents whose field type matches the query value
Example 1:
Example 2:
Originally, documents that do not contain query fields will be obtained. After adding this condition, documents that do not contain query fields will not be queried:
Example 3:
Example 4:
2.2.6 Array Operators
allExamples:
elemMatch example:
2.3 Document Cursors
Execution db.集合.find()
returns a cursor of a collection of documents: var myCursor = db.集合.find()
, without iterating over the cursor, only the first 20 documents are listed.
You can use cursor subscripts to directly access a document in the document collection:
After traversing all documents in the cursor, or after 10 minutes, the cursor closes automatically.
Cursor function:
-
hasNext & next
-
forEach
-
limit & skip
Note:
limit(0)
Indicates that all results are returned. -
count
Basic syntax:
cursor.count(<boolean>)
, if the parentheses are empty, the default is false.When the parentheses are false, both limit and skip are invalid; when the parentheses are true, the effects of limit and skip are used:
-
sort
1 means forward sorting from small to large, -1 means reverse sorting from large to small:
-
Two points of attention
- skip executes before limit
- sort is executed before skip and limit
Document projection:
Use document projection to return only some of the fields of the document: 1 to return, 0 to not return:
Note: In addition to the document primary key, it is not possible to use both contain and exclude projection operations:
2.4 Update documentation
Basic syntax:
db.集合.update(<query>, <update>, <options>)
- query defines the filter conditions of the updated document, which is consistent with the filter conditions in find
- update defines the update result
- options defines some parameters of the update operation
Note: All three of the above are optional.
Example:
If the optional <update> does not contain any update operators, the update command will directly replace the corresponding entire document (all fields) in the collection with the <update> document :
Notice:
- The primary key field cannot be changed. If the primary key field must be used, the value of the primary key field in <update> must be consistent with the original content.
- If multiple documents can match <query>, using <update> without an update operator to update the entire document will only update the first document.
Update operator:
If the optional <update> contains an update operator, the update command will replace the specific field of the corresponding document in the collection with the <update> document :
$set:
Update or add fields:
Update fields in an array:
Note: If the insertion exceeds the range of the array, resulting in empty spaces in the array, the empty spaces are filled with null by default.
$unset:
Delete fields:
Note: If you delete an array element, the length of the array will not be changed, but only the corresponding element will be set to null.
$rename:
Rename the document:
-
If you rename a non-existing document, the content of the original document will not be changed
-
If the new field name already exists, the field with the same name in the original document will be unset, and the field to be modified will be renamed
-
Inline document renaming:
Note: For embedded arrays, this method cannot be used and an error will be reported.
$inc & $mul:
Notice:
- These two commands can only work on numeric fields
- When acting on a field that does not exist, the field
$inc
will be created, and the field value will be set to the specified increment or decrement value;$mul
the field will be created, but the field value will be 0
$min & $max:
Update the value after comparing the original document value with the new value:
Note: If the updated field does not exist, these two commands will create the field with the updated value.
Array update operator:
These operators only work on array fields:
$addToSet:
Notice:
-
This command will no longer insert duplicate values if the value to be inserted already exists in the array field
-
When this command inserts a document or an array, the content in the same order is not considered to be duplicated
-
Add multiple values at once:
$pop:
Delete the first or last element of an array field, 1 means delete the last element, -1 means delete the first element:
Note: After deleting the last element in the array, the array will be empty.
$pull & $pullAll:
Remove a specific element from an array field:
$push:
Add elements to an array field:
2.5 Deleting documents
Basic syntax:
db.集合.remove(<query>, <options>)
- query: query condition
- Empty filter condition means delete all documents
- options: parameters of the delete operation
By default, the remove
command will delete all documents that meet the filter conditions. If you only want to delete the first document that meets the filter conditions, you can use the justOne
parameter :
2.6 Deleting a collection
remove
The command can delete all documents in the collection, but it will not delete the collection. The way to delete the collection is as follows: