The use of MongoDB and CRUD operations

MongoDB

1. Basic introduction

concept

MongoDB is a non-relational database that stores JSON documents. The structure is as follows:

image-20211030224316478

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 _idfield :

  • 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()

2.1 Creating documents

  • use db.集合.insert()or db.集合.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 itself
  • writeConcern: <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" : trueIndicates 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:

image-20211031002028387

An error occurred:

image-20211031002210468

Exceptions can be caught:

image-20211031002247779

The exception message printed by the library function print is more intuitive:

image-20211031002401481

Automatically generate primary key id

Just omit the _idfield :

image-20211031002536190

Create multiple documents

Basic syntax:

image-20211031002610211
  • 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:

image-20211031003020892

If insertMany encounters an error

image-20211031003257326
  • 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:

image-20211031003551219

Example:

image-20211031003622946

save command

Basic syntax:

image-20211031003702958
  • When the save instruction processes a new document, the insert instruction is called

composite primary key

image-20211031004104293
  • 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>)

  • queryIndicates the query condition in JSON format (optional), if it is empty, it means there is no query condition, that is, all documents are queried
  • projectionRepresents 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

image-20211031101911250 image-20211031102319210

2.2.3 Comparison Operators

image-20211031102433257 image-20211031141542785

** 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:

image-20211031102527757

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:

image-20211031141508493

Example 3:

image-20211102205501853

Notice:

  1. The value corresponding to the in and nin operators should be placed in an array
  2. nin filters out documents that do not contain the query field

Example 4:

in is used in conjunction with regular expressions:

image-20211115214303522

2.2.4 Logical Operators

image-20211102205732190

** Note: **Using logical operators requires an additional layer of curly braces.

Example 1:

image-20211102205856227

** Note: **not will also filter out documents that do not contain the query field.

Example 2:

image-20211102210014928

Simplified writing 1 (used on different fields):

image-20211102210237250

Simplified writing 2 (used on the same field):

image-20211102210314660

Example 3:

image-20211102210425505

** 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:

image-20211102210642158

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:

image-20211102210746866

Example 3:

image-20211102210939164

Example 4:

image-20211102211005913

2.2.6 Array Operators

image-20211115213031171

allExamples:

image-20211115213648847

elemMatch example:

image-20211115213922603

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:

image-20211115214721234

After traversing all documents in the cursor, or after 10 minutes, the cursor closes automatically.

image-20211115214828765

Cursor function:

  1. hasNext & next

    image-20211115214942657
  2. forEach

    image-20211115214954606
  3. limit & skip

    image-20211115215229209

    Note:limit(0) Indicates that all results are returned.

  4. 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:

    image-20211116211525122
  5. sort

    1 means forward sorting from small to large, -1 means reverse sorting from large to small:

    image-20211116211644258
  6. Two points of attention

    • skip executes before limit
    • sort is executed before skip and limit
    image-20211116211923609

Document projection:

Use document projection to return only some of the fields of the document: 1 to return, 0 to not return:

image-20211116213311315

Note: In addition to the document primary key, it is not possible to use both contain and exclude projection operations:

image-20211116213746785

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 :

image-20211116221939312

Notice:

  1. 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.
  2. 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 :

image-20211116222411862

$set:

Update or add fields:

image-20211117171504119

Update fields in an array:

image-20211117171742325

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:

image-20211117172341362

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:

image-20211117173038137
  1. If you rename a non-existing document, the content of the original document will not be changed

  2. 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

  3. Inline document renaming:

    image-20211117173752956

    Note: For embedded arrays, this method cannot be used and an error will be reported.

$inc & $mul:

image-20211117174144585 image-20211117174208498

Notice:

  1. These two commands can only work on numeric fields
  2. When acting on a field that does not exist, the field $incwill be created, and the field value will be set to the specified increment or decrement value; $multhe 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:

image-20211117175326205

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:

image-20211117175840513

$addToSet:

image-20211117180116819

Notice:

  1. This command will no longer insert duplicate values ​​if the value to be inserted already exists in the array field

  2. When this command inserts a document or an array, the content in the same order is not considered to be duplicated

  3. Add multiple values ​​at once:

    image-20211117180533783 image-20211117180606440

$pop:

Delete the first or last element of an array field, 1 means delete the last element, -1 means delete the first element:

image-20211117211436683

Note: After deleting the last element in the array, the array will be empty.

$pull & $pullAll:

Remove a specific element from an array field:

image-20211117212353876 image-20211117212447740

$push:

Add elements to an array field:

image-20211117212546401

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
image-20211117212755912

By default, the removecommand 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 justOneparameter :

image-20211117213023249

2.6 Deleting a collection

removeThe command can delete all documents in the collection, but it will not delete the collection. The way to delete the collection is as follows:

image-20211117213123837

Guess you like

Origin blog.csdn.net/weixin_49343190/article/details/121388500