One sentence a day
There should be a better way to start a day than waking up every morning.
There should be a better way to start a day than waking up every morning.
Database operation
query data base
View all databases
To view all databases, you can use the show dbs or show databases commands
> show dbs admin 0.000GB config 0.000GB local 0.000GB > show databases
View current database
View current database name: db command
> db test >
Create or switch databases
grammar
Syntax format of MongoDB database creation: use DATABASE_NAME if the database does not exist, create the database, otherwise switch to the specified database.
example
In the following example, we created the database test
> use test1 switched to db test1 > db test > show dbs admin 0.000GB config 0.000GB local 0.000GB
You can see that the database runoob we just created is not in the database list. To display it, we need to insert some data into the runoob database.
> db.runoob.insert({"name":"The rookie is me"}) WriteResult({ "nInserted" : 1 }) > show dbs admin 0.000GB config 0.000GB local 0.000GB test1 0.000GB
The default database in MongoDB is test. If you do not create a new database, the collection will be stored in the test database.
Delete database
grammar
Syntax format of MongoDB deleting database: dB dropDatabase()
example
In the following example, we deleted the database test1.
# First, view all databases > show dbs admin 0.000GB config 0.000GB local 0.000GB test 0.000GB test1 0.000GB # Switch to database test1 > use test1 switched to db test1 # Execute delete command > db.dropDatabase() { "ok" : 1 } # Check whether the database test1 still exists > show dbs admin 0.000GB config 0.000GB local 0.000GB test 0.000GB >
Collection operation
Collection, similar to a table in a relational database.
It can be created explicitly or implicitly.
View collection
View the tables / collections in the current library: show tables or show collections
> show collections mycollection > show tables mycollection >
Create collection
Explicitly create a collection
Syntax format: dB createCollection(name)
Parameter Description:
- Name - the name of the collection to create
Example: create a common collection named mycollection.
> db.createCollection("mycollection") { "ok" : 1 } > show tables mycollection
Naming convention for sets reference: naming convention for sets
Implicitly create a collection
When it is enough to insert a document into a collection, if the collection does not exist, the collection is automatically created.
For details, see: Tips
Usually we can create documents implicitly.
Delete collection
Syntax format: db The name of a collective collection drop()
Return value: if the selected collection is deleted successfully, the drop() method returns true; otherwise, it returns false.
Example: to delete the mycollection collection
> show tables mycollection > db.mycollection.drop() true > show tables >
Document operation
The data structure of a document is basically the same as JSON.
All data stored in the collection is in BSON format. For an introduction to BSON, you can view: data model
consult your documentation
Syntax format: dB collection. find(<query>, [projection])
Parameter Description:
Parameter | Type | Description |
query | document | Optional. Use query operators to specify selection filters. To return all documents in the collection, omit this parameter or pass an empty document ({}). |
projection | document | Optional. Specify the fields (projections) to return in documents that match the query filter. To return all fields in a matching document, omit this parameter |
Example 1: query all dB comment. Find() or dB comment. find({})
> db.comment.find() { "_id" : ObjectId("61bfc69ab5617497c0621b00"), ... } { "_id" : "1", "articleid" : "100001", ... } { "_id" : "2", "articleid" : "100001", ... } { "_id" : "3", "articleid" : "100001", ... } { "_id" : "4", "articleid" : "100001", ... } { "_id" : "5", "articleid" : "100001", ... } > db.comment.find({}) { "_id" : ObjectId("61bfc69ab5617497c0621b00"), ... } { "_id" : "1", "articleid" : "100001", ... } { "_id" : "2", "articleid" : "100001", ... } { "_id" : "3", "articleid" : "100001", ... } { "_id" : "4", "articleid" : "100001", ... } { "_id" : "5", "articleid" : "100001", ... } # To query according to certain conditions, you only need to add parameters in find() > db.comment.find({userid:'1003'}) { "_id" : "4", "articleid" : "100001", "userid" : "1003", ... } { "_id" : "5", "articleid" : "100001", "userid" : "1003", ... } >
Tip: each document will have a name called_ id field, which is equivalent to the primary key of the table in our original relational database. When you do not specify this field when inserting a document record, MongoDB will automatically create it, and its type is ObjectID.
Example 2: Projection Query: to return some specified fields from query results, you need to use Projection Query
# Query results are displayed only_ id,userid,nickname > db.comment.find({userid:"1003"},{userid:1,nickname:1}) { "_id" : "4", "userid" : "1003", "nickname" : "Caesar" } { "_id" : "5", "userid" : "1003", "nickname" : "Caesar" } # The query result only displays, userid and nickname, but not_ id > db.comment.find({userid:"1003"},{userid:1,nickname:1,_id:0}) { "userid" : "1003", "nickname" : "Caesar" } { "userid" : "1003", "nickname" : "Caesar" } # Query all data, but only display_ id,userid,nickname > db.comment.find({},{userid:1,nickname:1}) { "_id" : ObjectId("61bfc69ab5617497c0621b00"), "userid" : "1001", "nickname" : "Rose" } { "_id" : "1", "userid" : "1002", "nickname" : "Forget in the Jianghu" } { "_id" : "2", "userid" : "1005", "nickname" : "She is haggard" } { "_id" : "3", "userid" : "1004", "nickname" : "Captain Jack" } { "_id" : "4", "userid" : "1003", "nickname" : "Caesar" } { "_id" : "5", "userid" : "1003", "nickname" : "Caesar" } >
Insert document
Insert a single document
Use the insert() or save() methods to insert documents into the collection.
Syntax format: dB collection. insert( <document or array of documents>, { writeConcern: <document>, ordered: <boolean> } )
Parameter Description:
Parameter | Type | Description |
document | document or array | The document or array of documents to insert into the collection. (json format) |
writeConcern | document | Optional. A document expressing the write concern. Omit to use the default write concern.See Write Concern.Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transactions and Write Concern. |
ordered | boolean | Optional. If true, the documents in the array are inserted sequentially. If one of the documents has an error, MongoDB will return without processing the remaining documents in the array. If false, the unordered insertion is performed, and if one of the documents has an error, the main document in the array continues to be processed. It defaults to true in version 2.6 + |
Example: insert a piece of test data into the set (table) of comment
> db.comment.insert({"articleid":"100000","content":"It's a nice day and sunny today","userid":"1001","nickname":"Rose","createdatetime":new Date(),"likenum":NumberInt(10),"state":null}) WriteResult({ "nInserted" : 1 }) >
Tips
- If the comment collection does not exist, it is created implicitly
- The number in MongoDB is double by default. If you want to save an integer, you must use the function numberint (integer number), otherwise there will be a problem getting it out.
- Insert the current date using new Date()
- The inserted data is not specified_ id, the primary key value will be automatically generated
- If a field has no value, it can be assigned null or not written
After execution, insert a piece of data successfully as follows.
WriteResult({ "nInserted" : 1 })
be careful
- The key / value pairs in the document are ordered.
- The value in the document can be not only a string in double quotation marks, but also several other data types (even the entire embedded document).
- MongoDB is case sensitive and type sensitive
- MongoDB documents cannot have duplicate keys. The key of the document is a string. With a few exceptions, keys can use any UTF-8 character.
For document key naming conventions, see: document naming conventions
Batch insert document
Syntax format: dB collection. insertMany( [ <document 1> , <document 2>, ... ], { writeConcern: <document>, ordered: <boolean> } )
Parameter description
Parameter | Type | Description |
document | document or array | The document or array of documents to insert into the collection. (json format) |
writeConcern | document | Optional. A document expressing the write concern. Omit to use the default write concern.See Write Concern.Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transactions and Write Concern. |
ordered | boolean | Optional. A Boolean value that specifies whether Mongod instances should perform ordered or unordered inserts. The default is true. |
Example: batch insert multiple article comments
> db.comment.insertMany([ {"_id":"1","articleid":"100001","content":"We should not waste the morning on mobile phones. Health is very important. A cup of warm water is happy for you, me and him.","userid":"1002","nickname":"Forget in the Jianghu","createdatetime":new Date("2019-08- 05T22:08:15.522Z"),"likenum":NumberInt(1000),"state":"1"}, {"_id":"2","articleid":"100001","content":"I drink cold boiled water on an empty stomach in summer and warm boiled water in winter","userid":"1005","nickname":"She is haggard","createdatetime":new Date("2019-08-05T23:58:51.485Z"),"likenum":NumberInt(888),"state":"1"}, {"_id":"3","articleid":"100001","content":"I always drink cold boiled water in winter and summer.","userid":"1004","nickname":"Captain Jack","createdatetime":new Date("2019-08-06T01:05:06.321Z"),"likenum":NumberInt(666),"state":"1"}, {"_id":"4","articleid":"100001","content":"Experts say you can't eat on an empty stomach, which will affect your health.","userid":"1003","nickname":"Caesar","createdatetime":new Date("2019-08-06T08:18:35.288Z"),"likenum":NumberInt(2000),"state":"1"}, {"_id":"5","articleid":"100001","content":"Research shows that you must not drink freshly boiled water because it burns your mouth.","userid":"1003","nickname":"Caesar","createdatetime":new Date("2019-08- 06T11:01:02.521Z"),"likenum":NumberInt(3000),"state":"1"} ]); { "acknowledged" : true, "insertedIds" : [ "1", "2", "3", "4", "5" ] }
Tips
- Specified when inserting_ id, the primary key is the value.
- If a data insertion fails, the insertion will be terminated, but the successfully inserted data will not be rolled back.
Because batch insertion is prone to failure due to a large amount of data, try catch can be used to catch exceptions, which can not be handled during testing. If (understand):
> try { db.comment.insertMany([ {"_id":"1","articleid":"100001","content":"We should not waste the morning on mobile phones. Health is very important. A cup of warm water is happy for you, me and him.","userid":"1002","nickname":"Forget in the Jianghu","createdatetime":new Date("2019-08- 05T22:08:15.522Z"),"likenum":NumberInt(1000),"state":"1"}, {"_id":"2","articleid":"100001","content":"I drink cold boiled water on an empty stomach in summer and warm boiled water in winter","userid":"1005","nickname":"She is haggard","createdatetime":new Date("2019-08-05T23:58:51.485Z"),"likenum":NumberInt(888),"state":"1"}, {"_id":"3","articleid":"100001","content":"I always drink cold boiled water in winter and summer.","userid":"1004","nickname":"Captain Jack","createdatetime":new Date("2019-08-06T01:05:06.321Z"),"likenum":NumberInt(666),"state":"1"}, {"_id":"4","articleid":"100001","content":"Experts say you can't eat on an empty stomach, which will affect your health.","userid":"1003","nickname":"Caesar","createdatetime":new Date("2019-08-06T08:18:35.288Z"),"likenum":NumberInt(2000),"state":"1"}, {"_id":"5","articleid":"100001","content":"Research shows that you must not drink freshly boiled water because it burns your mouth.","userid":"1003","nickname":"Caesar","createdatetime":new Date("2019-08- 06T11:01:02.521Z"),"likenum":NumberInt(3000),"state":"1"} ]); } catch (e) { print (e); } BulkWriteError({ "writeErrors" : [ { "index" : 0, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: test1.comment index: _id_ dup key: { _id: \"1\" }", "op" : { "_id" : "1", "articleid" : "100001", "content" : "We should not waste the morning on mobile phones. Health is very important. A cup of warm water is happy for you, me and him.", "userid" : "1002", "nickname" : "Forget in the Jianghu", "createdatetime" : ISODate("0NaN-NaN-NaNTNaN:NaN:NaNZ"), "likenum" : NumberInt(1000), "state" : "1" } } ], "writeConcernErrors" : [ ], "nInserted" : 0, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) >
Update document
Syntax format: dB collection. Update (query, update, options) or dB collection. update( <query>, <update>, { upsert: <boolean>, multi: <boolean>, writeConcern: <document>, collation: <document>, arrayFilters: [ <filterdocument1>, ... ], hint: <document|string> // Available starting in MongoDB 4.2 } )
parameter
Tip: focus on the first four parameters
example
# Overwriting the modification will delete other fields not specified in the execution statement > db.comment.update({_id:"1"},{likenum:NumberInt(1001)}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.comment.find({_id:"1"}) { "_id" : "1", "likenum" : 1001 } > # Local modification. In order to solve the above problem, we need to use the modifier $set to implement it > db.comment.update({_id:"2"},{$set:{likenum:NumberInt(889)}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.comment.find({_id:"2"}) { "_id" : "2", "articleid" : "100001", ... } > # The nickname of the user whose user is 1003 is modified and updated in batch is Caesar the great ## By default, only the first data is updated > db.comment.update({userid:"1003"},{$set:{nickname:"Caesar 2"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.comment.find({userid:"1003"}) { "_id" : "4", "articleid" : "100001", "nickname" : "Caesar 2", ... } { "_id" : "5", "articleid" : "100001", "nickname" : "Caesar", ... } > ## To modify all qualified data, you need to specify the parameter {multi:true} > db.comment.update({userid:"1003"},{$set:{nickname:"Caesar the great"}},{multi:true}) WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 }) > db.comment.find({userid:"1003"}) { "_id" : "4", "articleid" : "100001", "nickname" : "Caesar the great", ... } { "_id" : "5", "articleid" : "100001", "nickname" : "Caesar the great", ... } > # Modification of column value growth: if we want to increase or decrease a column value based on the original value, we can use the $inc operator. ## The number of likes for data No. 3 is incremented by 1 each time > db.comment.find({_id:"3"}) { "_id" : "3", "likenum" : 667, ... } > db.comment.update({_id:"3"},{$inc:{likenum:NumberInt(1)}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.comment.find({_id:"3"}) { "_id" : "3", "likenum" : 668, ... } >
remove document
Syntax format: db Set name Remove (condition)
example
# Delete_ Record with id=1 > db.comment.remove({_id:"1"}) WriteResult({ "nRemoved" : 1 }) > db.comment.find({_id:"1"}) > # All data can be deleted. Please use it with caution > db.comment.find({}) { "_id" : ObjectId("61bfc69ab5617497c0621b00"), "articleid" : "100000", ... } { "_id" : "2", "articleid" : "100001", ... } { "_id" : "3", "articleid" : "100001", ... } { "_id" : "4", "articleid" : "100001", ... } { "_id" : "5", "articleid" : "100001", ... } > db.comment.remove({}) WriteResult({ "nRemoved" : 5 }) > db.comment.find({}) >
More query methods
The above introduces some basic queries about documents, and then we learn some ways to use queries.
Statistical query
The statistical query uses the count() method.
Syntax format: dB collection. count(query, options)
Parameter Description:
Parameter | Type | Description |
query | document | Query selection criteria. |
options | document | Optional. Additional options for modifying the count. |
example
# Count all records > db.comment.count() 5 > # Statistics by condition: count the number of records with userid 1003 > db.comment.count({userid:"1003"}) 2 >
Paging list query
You can use the limit() method to read the specified amount of data and the skip() method to skip the specified amount of data.
Syntax format: dB COLLECTION_ NAME. find(). limit(NUMBER). skip(NUMBER)
example
# Return the specified number of records: call limit to return the result (TopN). The default value is 20 > db.comment.find().limit(3) { "_id" : "1", "articleid" : "100001", ... } { "_id" : "2", "articleid" : "100001", ... } { "_id" : "3", "articleid" : "100001", ... } > # The skip method also accepts a numeric parameter as the number of records skipped. (not for the first N), the default value is 0 > db.comment.count() 5 > db.comment.find().skip(3) { "_id" : "4", "articleid" : "100001", ...} { "_id" : "5", "articleid" : "100001", ...} > # Paging query: 2 for each page, starting from the second page: skip the first two pieces of data, and then display 3 and 4 pieces of data > db.comment.find().skip(0).limit(2) { "_id" : "1", "articleid" : "100001", ....} { "_id" : "2", "articleid" : "100001", ....} > db.comment.find().skip(2).limit(2) { "_id" : "3", "articleid" : "100001", ....} { "_id" : "4", "articleid" : "100001", ....} > db.comment.find().skip(4).limit(2) { "_id" : "5", "articleid" : "100001", ....} >
Sort query
The sort() method sorts the data. The sort() method can specify the fields to be sorted by parameters and specify the sorting method by using 1 and - 1, where 1 is ascending and - 1 is descending.
Syntax format: dB COLLECTION_ NAME. find(). sort({KEY:1})
example
# Rank userid s and visits > db.comment.find().sort({userid:-1,likenum:1}) { "_id" : "2", "userid" : "1005", "likenum" : 888, ...} { "_id" : "3", "userid" : "1004", "likenum" : 666, ...} { "_id" : "4", "userid" : "1003", "likenum" : 2000, ...} { "_id" : "5", "userid" : "1003", "likenum" : 3000, ...} { "_id" : "1", "userid" : "1002", "likenum" : 1000, ...} > db.comment.find().sort({likenum:1}) { "_id" : "3", "userid" : "1004", "likenum" : 666, ...} { "_id" : "2", "userid" : "1005", "likenum" : 888, ...} { "_id" : "1", "userid" : "1002", "likenum" : 1000, ...} { "_id" : "4", "userid" : "1003", "likenum" : 2000, ...} { "_id" : "5", "userid" : "1003", "likenum" : 3000, ...} > db.comment.find().sort({userid:-1,likenum:-1}) { "_id" : "2", "userid" : "1005", "likenum" : 888, ...} { "_id" : "3", "userid" : "1004", "likenum" : 666, ...} { "_id" : "5", "userid" : "1003", "likenum" : 3000, ...} { "_id" : "4", "userid" : "1003", "likenum" : 2000, ...} { "_id" : "1", "userid" : "1002", "likenum" : 1000, ...} >
Tip: when skip(), family (), sort() are executed together, the order of execution is sort(), then skip(), and finally the displayed limit(), which is independent of the command writing order.
Regular conditional query
The fuzzy query of MongoDB is realized by regular expression.
Syntax format: db Assemble find({field: / regular expression /})
Tip: regular expression is the syntax of js, which is written directly.
example
# Query all documents with "boiled water" in the comments > db.comment.find({content:/boiling water/}) { "_id" : "2", "articleid" : "100001", "content" : "I drink cold boiled water on an empty stomach in summer and warm boiled water in winter", ... } { "_id" : "3", "articleid" : "100001", "content" : "I always drink cold boiled water in winter and summer.", ... } # Query comments that begin with "expert" > db.comment.find({content:/^expert/}) { "_id" : "4", "articleid" : "100001", "content" : "Experts say you can't eat on an empty stomach, which will affect your health.", ... } >
Comparison query
<, < =, >, > = this operator is also very common.
Syntax format
db.Set name.find({ "field" : { $gt: value }}) // Greater than: field > value db.Set name.find({ "field" : { $lt: value }}) // Less than: field < value db.Set name.find({ "field" : { $gte: value }}) // Greater than or equal to: field > = value db.Set name.find({ "field" : { $lte: value }}) // Less than or equal to: field < = value db.Set name.find({ "field" : { $ne: value }}) // Not equal to: field= value
example
# Query records with more than 700 comments and likes > db.comment.find({likenum:{$gt:NumberInt(700)}}) { "_id" : "1", "articleid" : "100001", ... , "likenum" : 1000, "state" : "1" } { "_id" : "2", "articleid" : "100001", ... , "likenum" : 888, "state" : "1" } { "_id" : "4", "articleid" : "100001", ... , "likenum" : 2000, "state" : "1" } { "_id" : "5", "articleid" : "100001", ... , "likenum" : 3000, "state" : "1" } >
Conditional join query
If we need to query more than two conditions at the same time, we need to use the $and operator to correlate the conditions. (equivalent to and of SQL)
If more than two conditions are or related, we use the $or operator to associate them
Syntax format: $and: [{}, {}, {}], $or: [{}, {}, {}]
example
# Query documents with likenum greater than or equal to 700 and less than 2000 in the comment collection > db.comment.find({$and:[{likenum:{$gte:NumberInt(700)}},{likenum:{$lt:NumberInt(2000)}}]}) { "_id" : "1", "articleid" : "100001", ... , "likenum" : 1000, "state" : "1" } { "_id" : "2", "articleid" : "100001", ... , "likenum" : 888, "state" : "1" } # Query the document records with userid of 1003 or the number of likes less than 1000 in the comment collection > db.comment.find({$or:[ {userid:"1003"} ,{likenum:{$lt:1000} }]}) { "_id" : "2", ... , "userid" : "1005", "likenum" : 888, "state" : "1" } { "_id" : "3", ... , "userid" : "1004", "likenum" : 666, "state" : "1" } { "_id" : "4", ... , "userid" : "1003", "likenum" : 2000, "state" : "1" } { "_id" : "5", ... , "userid" : "1003", "likenum" : 3000, "state" : "1" } >
Beautiful sentences
There was a passage in the Oxford maxim that impressed me deeply: "if we just want to be happy, it is easy to achieve. But if we want to be happier than others, we will find it difficult to achieve. Because our imagination of others' happiness always exceeds our actual situation."
We often complain that there are too many disappointments in life and always feel that our fate is inferior to others. But in fact, the biggest unhappiness of people is that they don't know contentment.
Hello, I am yltrcc, sharing technical points everyday. Welcome to my official account: ylcoder