This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge! This article is to learn the syntax of mongodb database
Database connection
Backend database connection syntax:
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
Copy the code
- Mongodb ://
- After that is the optional username and password,
- Host is the address of the server to connect to,
- Portx is the specified port, 27017 by default
- Database If username:password@ is specified, connect and verify the login to the specified database. If this parameter is not specified, the test database is opened by default.
- Options is the connection option. If /database is not used, you need to add /. All connection options are key-value pairs name=value, which are separated by & or; (semicolon)
For example, use user name niu and password root to log in to the project database at localhost.
mongodb://niu:root@localhost/project
Copy the code
Creating a database
Creating a database
use project2
db
Copy the code
Results the following
Display all databases
show dbs
Copy the code
Insert a piece of data into project2
db.project2.insert({"name":"11111"})
show dbs
Copy the code
The results are as follows
Deleting a database
db.dropDatabase()
show dbs
Copy the code
The result is as follows: The Project2 database has been deleted
Create a collection
use test
db.createCollection("project2")
Copy the code
The Test database is created, and the Test database creates the Project2 collection
Delete the collection
db.project2.drop()
Copy the code
Inserted into the document
db.COLLECTION_NAME.insertOne(document)
db.COLLECTION_NAME.replaceOne(document)
Copy the code
There are three parameters:
- Document Specifies the Document to write to.
- WriteConcern Write policy. The default value is 1, indicating that the write operation is required. 0 is not required.
- Ordered specifies whether to write in order. The default is true.
db.demo1.insertOne({title: 'title'.description: 'description'.arr: ['1'.'2'.'3'],})Copy the code
Update the document
MongoDB uses the update() and save() methods to update documents in the collection
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>})Copy the code
- Query: indicates an UPDATE query condition, similar to that after WHERE in an SQL update query.
- Update: The update object and some update operators (e.g.,,,inc…) In SQL update query
- Upsert: Optional. This parameter means whether to insert objNew if there is no record of update. True means insert, default is false, and do not insert.
- Multi: Optional. The default value is false and mongodb updates only the first record found. If this parameter is true, all the records found by the condition will be updated.
- WriteConcern: Optional, the level of the exception to be thrown.
db.demo1.update({'title':'title'}, {$set: {'title':'title-Update'}}, {multi:true})
db.demo1.find().pretty()
Copy the code
Here are the results:
Delete the document
db.collection.remove(
<query>,
{
justOne: <boolean>,
writeConcern: <document>})Copy the code
Query :(optional) condition of the document to be deleted. JustOne: (Optional) If set to true or 1, only one document is deleted, if not set, or if the default value false is used, all documents matching the criteria are deleted. WriteConcern :(optional) the level of the exception to be thrown.
db.demo1.remove({'title':'title'},1)
db.demo1.find()
Copy the code
From three pieces of data, delete to two
Query the document
db.collection.find(query, projection)
Copy the code
- Query: Optional. The query operator is used to specify the query conditions
- Projection: Optional, using the projection operator to specify the returned key. Return all key values in the document when querying, just omit this parameter (default omitted)
db.demo1.find().pretty()
Copy the code
And condition query
db.col.find({key1:value1, key2:value2}).pretty()
Copy the code
db.demo1.find({'title':'title3'.'description':'description'}).pretty()
Copy the code
Or conditions
db.demo1.find({$or: [{"title":"title2"}, {"title": "title3"}]}).pretty()
Copy the code
Conditional operator
Insert three pieces of data first
More than >
db.demo1.find({likes : {$gt : 1}})
Copy the code
The results are as follows
Greater than or equal to greater than or equal to
db.demo1.find({likes : {$gte : 1}})
Copy the code
< <
db.demo1.find({likes : {$lt : 2}})
Copy the code
Less than or equal to <=
db.demo1.find({likes : {$lte : 2}})
Copy the code
Take the median
db.demo1.find({likes : {$lt :3.$gt : 1}})
Copy the code
The $type operators
Query data type Common Double, String, Object, Array, Boolean, Date, and so on
db.demo1.find({"likes" : {$type : 'number'}})
Copy the code
Limit and Skip methods
Limit Indicates the number of entries to be queried
db.demo1.find().limit(2)
Copy the code
Skip how many
db.demo1.find().limit(2).skip(1)
Copy the code
The sorting
1 is for ascending order, and -1 is for descending order.
db.demo1.find().sort({likes:1})
Copy the code
db.demo1.find().sort({likes: -1})
Copy the code
The index
db.collection.createIndex(keys, options)
Copy the code
If you want to create an index in descending order, you can specify -1 as the Key value.
db.demo1.createIndex({likes:1})
Copy the code
The aggregation
db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
Copy the code
db.demo1.aggregate([{$group : {_id : "$tags".num_tutorial : {$sum : 1}}}])
Copy the code
Calculate the tags have several in common
$sum specifies the sum.
Expression description instance
$sum specifies the sum.
db.demo1.aggregate([{$group : {_id : "$by_user".num_tutorial : {$sum : "$likes"}}}])
Copy the code
$AVg Calculates the average
db.demo1.aggregate([{$group : {_id : "$by_user".num_tutorial : {$avg : "$likes"}}}])
Copy the code
$min gets the minimum corresponding value for all documents in the collection
db.demo1.aggregate([{$group : {_id : "$by_user".num_tutorial : {$min : "$likes"}}}])
Copy the code
$Max gets the maximum value for all documents in the collection.
db.demo1.aggregate([{$group : {_id : "$by_user".num_tutorial : {$max : "$likes"}}}])
Copy the code
$push inserts values into an array in the result document.
db.demo1.aggregate([{$group : {_id : "$by_user".url : {$push: "$url"}}}])
Copy the code
$addToSet inserts values into an array in the result document, but does not create a copy.
db.demo1.aggregate([{$group : {_id : "$by_user".url : {$addToSet : "$url"}}}])
Copy the code
$first gets the first document data in the order of the resource document.
db.demo1.aggregate([{$group : {_id : "$by_user".first_url : {$first : "$url"}}}])
Copy the code
$last gets the last document data in the order of the resource document
db.demo1.aggregate([{$group : {_id : "$by_user".last_url : {$last : "$url"}}}])
Copy the code