1 Database \ set operation
1.1 Creating a Database
Syntax: use DATABASE_NAME Description: Switch to the specified database, and if the database does not exist, create a database instance with that name: Create a database named socialmedia
use socialmedia
Copy the code
Note that because the database is empty at this point, it will not show up in the database list.
1.2 Creating a Collection
Db.createcollection (name, options)
- Name: The name of the collection to be created
- Options: Specifies the memory size
Example: Create a collection named Douyin and Bilibili in Socialmedia’s database
db.createCollection("douyin")
db.createCollection("bilibili")
Copy the code
To see all the collections in the database, type show Collections. Enter show DBS to see the new database in the database list.
1.3 Deleting a Collection
Syntax: db.collection.drop() instance: Delete the Bilibili collection from Socialmedia’s database
db.bilibili.drop()
Copy the code
At this point, type show Collections again, and you can see that the collection Bilibili has been deleted
1.4 Deleting a Database
Syntax: db.dropDatabase() instance: Delete socialMedia database
use socialmedia
db.dropDatabase()
Copy the code
At this point, enter show DBS again, and you can see that the database Socialmedia has been deleted
2 Add, delete, and modify documents
2.1 Inserting a Document
Grammar:
- The insertOne() method inserts a document
db.collection.insertOne(
< document > ,
{
writeConcern: < document >
}
)
Copy the code
- The insertMany() method inserts multiple documents
db.collection.insertMany( [ < document1 > , < document2 > , ...] , { writeConcern: < document > , ordered: < boolean > } )Copy the code
- The insert() method is a combination of the first two methods, but the first two methods are recommended for better readability
Note: If you insert a document into a nonexistent collection, MongoDB automatically creates and names the collection, and then inserts the document.
- Document: The document to be inserted
- WriteConcern: indicates the write policy
- Ordered: Specifies whether to write in order
Example: Insert multiple documents into the Douyin collection of a Socialmedia library
Db.douyin. InsertMany ([{"aweme_id": 115615646865, "aweme_name": "aweme_name", "likes": 555, "follower": 3}, {"aweme_id": 11561564565, "aweme_name": "105 ° love ", "likes": 5545, "follower": 24}, {"aweme_id": 11561564565, "aweme_name": "105 ° love ", "likes": 5545, "follower": 24}, {"aweme_id": 115615325565, "aweme_name": "three sentences make a man spend 18W for me", "likes": 5545, "follower": 45}, {"aweme_id": 11561534265, "aweme_name": "Likes ": 666, "follower": 45}])Copy the code
At this point, enter db.douyin.find() again to view all the documents in the collection.
2.2 Updating Documents
Grammar:
db.collection.update(
< query > ,
< update > ,
{
upsert: < boolean > ,
multi: < boolean > ,
writeConcern: < document >
}
)
Copy the code
Description:
- Query: Indicates the update query condition
- Update: Indicates the update operation of the update object
- Upsert: Specifies whether to insert new data if no update object exists. The default value is no
- Multi: whether to update all the records that meet the conditions. By default, only the first data found is updated
- WriteConcern: Level of the exception to be thrown
Example: Change aweme_id to 88888888 in all documents whose “follower”=45 in the newly inserted four data pieces
db.douyin.update(
{"follower": 45},
{$set: {"aweme_id": 88888888}},
{multi: true}
)
Copy the code
At this time, enter db.douyin. Find () again, you can see that the data has been updated. If you do not write {multi:true}, then MongoDB will only update the first data found
2.3 Deleting a Document
Grammar:
- The deleteOne() method deletes only one qualified document
db.collection.deleteOne(
< filter > ,
{
writeConcern: < document > ,
collation: < document >
}
)
Copy the code
- The deleteMany() method deletes all documents that meet the criteria
db.collection.deleteMany(
< filter > ,
{
writeConcern: < document > ,
collation: < document >
}
)
Copy the code
- The remove() method, which is essentially a combination of the first two methods, has an extra justOne parameter to control the removal of only one or all, but the first two methods are recommended for code readability
Description:
- Filter: indicates the condition for filtering documents
- WriteConcern: Level of the exception to be thrown
- Collation: Specifies the collation used for the operation
Example: delete all documents in the Douyin collection with “aweme_id”=8888888
db.douyin.deleteMany({
"aweme_id": 88888888
})
Copy the code
Enter db.douyin.find() again, and you can see that the documents matching the conditions have been deleted
3 Document Query
3.1 the find () method
Db.collection. find(query, projection)
- Query: Use the query operator to specify the query conditions. If no query conditions are specified, use {} instead
- Projection: Specifies the key to return. This parameter has two modes:
- In inclusion mode, the input format, such as {title: 1}, uses 1 to indicate the field to be returned, and does not need to write the fields that do not need to be returned.
- In the Exclusion mode, enter a format such as {title: 0}. Use 0 to indicate fields that do not need to be returned. All other fields will be returned.
- Only the primary key
_id
This parameter is returned by default and must be specified actively_id: 0
To hide the primary key.
3.2 AND AND OR conditions
Grammar:
- AND conditions
db.collection.find({
key1: value1,
key2: value2
})
Copy the code
- OR conditions
db.collection.find(
{
$or: [
{key1: value1},
{key2: value2}
]
}
)
Copy the code
Description:
- The AND condition requires only multiple key-value pairs, separated by commas
- OR conditions require a keyword
$or
, pass the key-value pairs in as an array
3.3 Conditional operators
conditions | The operator | Directing a grammar | SQL syntax |
---|---|---|---|
Equal to (numerical judgment) | / | db.collection.find({key: value}) | where key = value |
Less than | $lt | db.collection.find({key: {$lt: value}}) | where key < value |
Less than or equal to | $lte | db.collection.find({key: {$lte: value}}) | where key <= value |
Is greater than | $gt | db.collection.find({key: {$gt: value}}) | where key > value |
Greater than or equal to | $gte | db.collection.find({key: {$gte: value}}) | where key >= value |
Is not equal to | $ne | db.collection.find({key: {$ne: value}}) | where key ! = value |
3.4 Other Methods
3.4.1 track limit () method
Syntax: db.collection.find().limit(number) Description: In the documents that match the query result, number documents are displayed.
3.4.2 skip () method
Syntax: db.collection.find().skip(number)
Rule 3.4.3 sort () method
Syntax: db.collection.find().sort({KEY:1})
3.5 For example, chestnuts
- Insert several documents into the Bilibili collection of the Socialmedia database
Use socialmedia db.bilibili. InsertMany ([{"aweme_id": 115615646865,"aweme_name": "like ": 555,"follower": 3}, {"aweme_id": 11561564565,"aweme_name": "105 ° love ","likes": 5545,"follower": 24}, {"aweme_id": 11561564565,"aweme_name": "105 ° love ","likes": 5545,"follower": 24}, {"aweme_id": 115615325565,"aweme_name": "three sentences make a man spend 18W for me","likes": 5545,"follower": 45}, {"aweme_id": 11561534265,"aweme_name": "Urga", "likes" : 666, the "followers" : 56}, {" aweme_id: "115615352525," aweme_name ":" A ", "likes" : 67, "followers" : 35}, {"aweme_id": 11561453434534,"aweme_name": "B","likes": 65646,"follower": 70}, {"aweme_id": 117987978975,"aweme_name": "C","likes": 666,"follower": 80} ])Copy the code
- If “likes” are greater than 1000 but less than 10000 or “follower” is different from 70 or 3, the “likes” and “aweme_name” fields are returned. The _id is not displayed. In the query result, the first document is skipped and only four documents are displayed in descending order of “likes”
db.bilibili.find(
{$or: [
{likes: {$gt: 1000, $lt: 10000}},
{follower: {$ne: 70, $ne: 3}}
]
},
{likes: 1,aweme_name: 1,_id: 0}
).sort({likes: -1}).skip(1).limit(4)
Copy the code
4 Aggregation Query
4.1 aggregate () method
- The aggregation function of MongoDB is to input the document into the processing pipeline, complete the operation on the document in the pipeline, and finally convert the document into the aggregation result.
- Aggregate () is like a process in an assembly line. The general process is from querying documents to calculating data.
Syntax: db.collection.aggregate(AGGREGATE_OPERATION)
- The aggregate() method needs to be used in conjunction with the pipe operator
- Basic pipe operations provide filters that act like queries and document transformations to modify the form of the output document
- Other pipe operations provide tools to group and sort documents by specific fields, as well as tools for aggregating array contents
- In addition, operators can be used in the pipeline phase to perform tasks such as calculating averages or connecting strings
4.2 Common Pipe operators
MongoDB’s aggregate pipeline passes MongoDB documents to the next pipeline after they have been processed. Pipeline operations can be used in combination. Using multiple pipeline operators requires passing in functions as arrays. Common pipeline operators in the aggregation framework are as follows:
- $project: Modify the structure of the input document. It can be used to rename, add, or delete fields, as well as to create computed results and to nest documents
- $match: Filters data and outputs only documents that match the criteria
- $limit: Used to limit the number of documents returned by the MongoDB aggregate pipeline
- $skip: Skips a specified number of documents in the aggregation pipeline and returns the remaining documents
- $unwind: unwinds an array type field in a document into multiple pieces, each containing a value from the array
- $group: Groups the documents in the collection, which can be used for statistical results
- $sort: Output the sorted input document
2 $project
See the projection parameter in the find() method for the basic $project format, but you can use the operator to do more:
The operator | function | instructions |
---|---|---|
$add | add | Numerical calculation |
$subtract | subtraction | Numerical calculation |
$multipy | The multiplication | Numerical calculation |
$divide | division | Numerical calculation |
$mod | modulus | Numerical calculation |
$concat | The connection | String operation |
$substr | The interception | String operation |
In addition, there are operators that handle relational and logical operations, which determine the size and type, and whether or not to return a Boolean value.
Example:
- Insert some documents into the Xiaohongshu collection in the SocialMeida library:
Use socialmedia db. Xiaohongshu. InsertMany ([{" author ":" aaa ", "aweme_name" : "michelle sweet city", "likes" : 555, "followers" : 3}, {" author ", "BBB", "aweme_name" : "105 degrees of love", "likes" : 5545, "followers" : 24}, {" author ":" BBB ", "aweme_name" : "Three words let a man as I spend 18 w", "likes" : 5545, "followers" : 45}, {" author ":" aaa ", "aweme_name" : "urga", "likes" : 666, "followers" : 56}, {" author ":" CCC ", "aweme_name" : "ha, ha, ha," "likes" : 67, "followers" : 35}, {" author ":" CCC ", "aweme_name" : "la la la", "likes" : 65646, "followers" : 70}, {" author ":" BBB ", "aweme_name" : "xi xi xi", "likes" : 666, "followers" : 80}])Copy the code
- Add the “author” and “aweme_name” fields to the format of “author– aweme_name” and name the field “A1”. Add the “likes” and “followers” and name the field “A2” :
db.xiaohongshu.aggregate({
$project: {
_id: 0,
A1: {"$concat": ["$author", "---", "$aweme_name"]},
A2: {"$add": ["$likes", "$follower"]}
}
})
Copy the code
4.2.2 $group
$group = ‘group by’; $group = ‘group by’;
The operator | function |
---|---|
$sum | Calculate the total |
$avg | Calculated mean |
$min | Calculate minimum |
$max | Calculate the maximum |
Example: Using the data from the previous section, calculate the number of works and average likes for each author in the Xiaohongshu collection in the SocialMeida library
Db. Xiaohongshu. Aggregate ({$group: {_id: "$author", "work for" : {1} $sum:, "average" : {$avg: "$" likes"}}})Copy the code
{$sum: 1} {$sum: 1}} {$sum: 1}
Holdings of $match
$match is similar to the query parameter in the find() method and is used only to filter data. Example: Using the data in the previous section, query “aweme_name” in the Xiaohongshu collection of the SocialMeida library for followers greater than 50.
db.xiaohongshu.aggregate([
{$project: {_id: 0, aweme_name: 1, follower: 1}},
{$match: {follower: {$gt: 50}}}
])
Copy the code
The code uses $project to select the fields that need to be displayed, and $match to filter the data, and vice versa