You may usually use client tools to connect and query mongodb during the development process, but generally the databases in production do not allow local client connections.
This article mainly explains how to connect to the mongodb server through the command line and use some simple query statements
Article directory
-
- 1. Connect to mongodb from the command line
- 2. Basic commands
-
- 2.1 Database operations
- 2.2 Basic commands for collections
- 2.3 Insert
- 2.4 Save
- 2.5 Query
- 2.6 Update
- 2.7 Delete
- 2.8 Comparison operators
- 2.9 Range operators
- 2.10 Logical operators
- 2.11 Regular expressions
- 2.12 limit and skip()
- 2.13 Sorting
- 2.14 Statistics
- 2.15 Eliminate duplication
- 3. Aggregation function operations
-
- 3.1 Commonly used pipelines
- 3.2 Expressions
- 3.3 $group
- 3.4 $project
- 3.5 $match
- 3.6 $sort
- 3.7 $limit
- 3.8 $skip
- 3.9 $unwind
1. Connect to mongodb from the command line
Let’s take a brief look at the mongosh command first:
root@bddff4197a79:/# mongosh --help $ mongosh [options] [db address] [file names (ending in .js or .mongodb)] Options: -h, --help Show this usage information -f, --file [arg] Load the specified mongosh script --host [arg] Server to connect to --port [arg] Port to connect to --version Show version information --verbose Increase the verbosity of the output of the shell --quiet Silence output from the shell during the connection process --shell Run the shell after executing files --nodb Don't connect to mongod on startup - no 'db address' [arg] expected --norc Will not run the '.mongoshrc.js' file on start up --eval [arg] Evaluate javascript --retryWrites Automatically retry write operations upon transient network errors Authentication Options: -u, --username [arg] Username for authentication -p, --password [arg] Password for authentication --authenticationDatabase [arg] User source (defaults to dbname) --authenticationMechanism [arg] Authentication mechanism --awsIamSessionToken [arg] AWS IAM Temporary Session Token ID --gssapiServiceName [arg] Service name to use when authenticating using GSSAPI/Kerberos --sspiHostnameCanonicalization [arg] Specify the SSPI hostname canonicalization (none or forward, available on Windows) --sspiRealmOverride [arg] Specify the SSPI server realm (available on Windows) TLS Options: --tls Use TLS for all connections --tlsCertificateKeyFile [arg] PEM certificate/key file for TLS --tlsCertificateKeyFilePassword [arg] Password for key in PEM file for TLS --tlsCAFile [arg] Certificate Authority file for TLS --tlsAllowInvalidHostnames Allow connections to servers with non-matching hostnames --tlsAllowInvalidCertificates Allow connections to servers with invalid certificates --tlsCertificateSelector [arg] TLS Certificate in system store (Windows and macOS only) --tlsCRLFile [arg] Specifies the .pem file that contains the Certificate Revocation List --tlsDisabledProtocols [arg] Comma separated list of TLS protocols to disable [TLS1_0,TLS1_1,TLS1_2] API version options: --apiVersion [arg] Specifies the API version to connect with --apiStrict Use strict API version mode --apiDeprecationErrors Fail deprecated commands for the specified API version FLE Options: --awsAccessKeyId [arg] AWS Access Key for FLE Amazon KMS --awsSecretAccessKey [arg] AWS Secret Key for FLE Amazon KMS --awsSessionToken [arg] Optional AWS Session Token ID --keyVaultNamespace [arg] database.collection to store encrypted FLE parameters --kmsURL [arg] Test parameter to override the URL of the KMS endpoint DB Address Examples: foo Foo database on local machine 192.168.0.5/foo Foo database on 192.168.0.5 machine 192.168.0.5:9999/foo Foo database on 192.168.0.5 machine on port 9999 mongodb://192.168.0.5:9999/foo Connection string URI can also be used File Names: A list of files to run. Files must end in .js and will exit after unless --shell is specified. Examples: Start mongosh using 'ships' database on specified connection string: $ mongosh mongodb://192.168.0.5:9999/ships For more information on usage: https://docs.mongodb.com/mongodb-shell.
You can see that mongosh has a lot of parameters. Below we demonstrate several commonly used parameters to test the connection to mongo
Connect to mongodb command
- –host is the remote server address and port
- -u is the username
- -p is password
mongosh --host localhost:27017 -u root -p 'yourpassword'
If there is no password, you can use it directly
mongosh --host localhost:27017
demo:
root@bddff4197a79:/# mongosh --host localhost:27017 Current Mongosh Log ID: 654b58d5a9821e4d7bbbf493 Connecting to: mongodb://localhost:27017/?directConnection=true &serverSelectionTimeoutMS=2000 Using MongoDB: 5.0.5 Using Mongosh: 1.1.6 For mongosh info see: https://docs.mongodb.com/mongodb-shell/ ------ The server generated these startup warnings when booting: 2023-11-08T01:13:10.562 + 00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem 2023-11-08T01:13:11.610 + 00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted ------ Warning: Found ~/.mongorc.js, but not ~/.mongoshrc.js. ~/.mongorc.js will not be loaded. You may want to copy or rename ~/.mongorc.js to ~/.mongoshrc.js.
2. Basic commands
2.1 Database operations
View all databases
show dbs
View the current database
db
Switch database or create database (switch if it exists, create if it does not exist)
use database name
Delete database
db.dropDatabase()
2.2 Basic commands of collections
Without manually creating a collection:
The first time you add data to a collection that does not exist, the collection will be created.
Create a collection manually:
db.createCollection(name, options)
db.createCollection(“stu”)
db.createCollection(“stb”, {capped:true, size:10})
Parameter clamped: The default value is false, which means no upper limit is set, and the value is true, which means setting an upper limit.
Parameter size: When the capped value is true, this parameter needs to be specified, indicating the upper limit size. When the document reaches the upper limit,
Will overwrite the previous data, unit is bytes
View the collection:
show collections
Delete the union:
db.Collection name.drop()
2.3 Insert
db.Collection name.insert(document)
db.stu.insert({name:'zhangsan', gender:1}) db.stu.insert({_id:"20170101", name:'zhangsan', gender:1})
When inserting a document, if you do not specify the _id parameter, MongoDB will assign a unique Objectid to the document.
2.4 Save
db.Collection name.save(document)
If the document’s _id already exists, modify it. If the document’s _id does not exist, add it.
2.5 Query
Method find() queries all
db.collection name.find({conditional document}) db.stu.find({name:'zhangsan'})
The method findOne() query returns only one
db.Collection name.findOne({Conditional document}) db.stu.findOne({age:20})
Method pretty() formats the result
db.Collection name.find({Conditional document}).pretty() db.stu.find({name:'zhangsan'}).pretty()
2.6 update
db.Collection name.update(,,{multi:})
1. Parameter query: query conditions
2. Parameter update: update operator
3. Parameter multi: optional, the default is false, which means that only the first record found is updated. The value of true means that all documents that meet the conditions are updated.
db.stu.update({name:'zhangsan', {name:'wangwu'}}) updates the first matching item, and other values will be deleted db.stu.update({name:'zhangsan', {$set:{name:'hys'}}}) updates the first matching item, other values will not be deleted db.stu.update{<!-- -->{}, {$set:{gender:0}}, {multi:true}} updates all, other values will not be deleted
2.7 Delete
db.Collection name.remove(, {justOne:})
1. Parameter query: optional, conditions for deleting documents
2. Parameter justOne: optional. If set to true or 1, only one item will be deleted. The default is false, which means multiple items will be deleted.
db.stu.remove({name:'wangwu'}, {justOne:true}) delete an item db.stu.remove({gender:2}) delete all
2.8 Comparison operators
Equal: The default is equal to judgment, no operator
Less than:
l
t
(
l
e
s
s
t
h
a
n
)
Less than or equal to:
lt (less than) less than or equal to:
lt (less than) less than or equal to: lte (less than equal)
more than the:
g
t
(
g
r
e
a
t
e
r
t
h
a
n
)
greater or equal to:
gt (greater than) greater than or equal to:
gt (greaterthan) greater than or equal to: gte (greater than equal)
Not equal to: $ne (not equal)
db.stu.find({age: {$gte:18}})
2.9 Range Operator
use ”
i
n
”
,
”
in”, ”
in”,”nin” determine whether it is within a certain range
Query students aged 18 and 28
db.stu.find({age:{$in:[18,28]}})
2.10 Logical operators
and: Just write multiple conditions in json
Query students whose age is greater than or equal to 18 and whose gender is 1
db.stu.find({age:{$gte:18}, sex:1})
or: Use “$or”, the value is an array, and each element in the array is json
Query students who are older than 18 or whose gender is 1
db.stu.find({$or:[{age:{$gt:18}}, {sex:1}]})
Query students who are older than 18, or whose gender is 1, and whose name is xiaoming
db.stu.find({$or:[{age:{$gt:18}}, {<!-- -->set:1}],name:'xiaoming'})
2.11 Regular Expressions
Write regular expressions using // or $regex
Search for students with the younger surname
db.stu.find({name:/^xiao/}) db.stu.find({name:{$regex:'^xiao'}})
2.12 limit and skip()
Method limit(): used to read a specified number of documents
db.Collection name.find().limit(number)
Query 2 pieces of student information
db.stu.find().limit(2)
Method skip(): used to skip a specified number of documents
db.Collection name.find().skip(number)
db.stu.find().skip(2)
use simultaneously
db.stu.find().limit(1).skip(2) db.stu.find().limit(2).skip(1)
2.13 Sorting
The method sort() is used to sort the collection
db.Collection name.find().sort({Field: 1,…})
Parameter 1 is sorted in ascending order
Parameter -1 bit descending order
Sort by gender in descending order, then by age in ascending order
db.stu.find().sort({sex:-1,age:1})
2.14 Statistics
Method count() is used to count the number of documents in the result set
db.Collection name.find({condition}).count()
db.Collection name.count({condition})
db.stu.find({sex:1}).count() db.stu.count({age:{$gt:20},sex:1})
2.15 Eliminate duplicates
Method distinct() deduplicates data
db.Collection name.distinct(Duplicate field’, {condition})
db.stu.distinct('sex', {age: {$gt:18}})
3. Aggregation function operations
3.1 Common Pipes
In mongodb, after the document is processed, the next processing is performed through the pipeline
Commonly used pipelines are as follows:
$group: Group documents in the collection and can be used for statistical results
$match: Filter data and only output documents that meet the conditions
$project: Modify the structure of the input document, such as renaming, adding, deleting fields, and creating calculation results
$sort: Sort the input documents and output them
$limit: Limit the number of documents returned by the aggregation pipeline
$skip: Skip the specified number of documents. and return the remaining documents
$unwind: Split array type fields
3.2 Expressions
Commonly used expressions:
$sum: Calculate the sum, $sum:1 means double the calculation
$avg: Calculate the average
$min: Get the minimum value
$max: Get the maximum value
$push: Insert values into an array in the resulting document
$first: Get the first document data according to the sorting of resource documents
$last: Get the last document data according to the sorting of resource documents
3.3 $group
Group documents in a collection, which can be used for statistical results
_id represents the basis for grouping, and the format of using a certain field is ‘$field’
Total number of statistical areas
db.map.aggregate( {$group:{_id: '$country',counter: {$sum:1}}} )
Group all documents in the collection into one group: find the total number of students and their average age
db.stu.aggregate( {$group:{_id: null , counter: {$sum:1},age_avg: {$avg: '$age'}}} )
3.4 $project
Query the student’s name and age
db.stu.aggregate( {$project:{_id:0,name:1,age:1}} )
Query the number of boys and girls and output the number
db.stu.aggregate( {$group:{_id:'$sex',counter:{$sum:1}}}, {$project:{_id:0, sex:'$_id',counter:1}} )
3.5 $match
Used for past data, only documents that meet the conditions are output.
Query students older than 20
db.stu.aggregate( {$match:{age:{$gt:20}}} )
Check the total number of boys and girls above 20 in your area
db.stu.aggregate( {$match:{age:{$gt:20}}}, {$group:{_id:'$sex', counter:{$sum:1}}} )
3.6 $sort
Sort input documents and output
Query student information and sort by age in ascending order
db.stu.aggregate( {$sort:{age:1}} )
Sorted by gender and sorted by number of people in descending order
db.stu.aggregate( {$group:{_id:'$sex',count:{$sum:1}}}, {$sort:{count:-1}}, {$project:{count:1,_id:0}})
3.7 $limit
Limit the number of documents returned by the aggregation pipeline
Query 2 pieces of student information
db.stu.aggregate( {$limit:2} )
3.8 $skip
Skips a specified number of documents and returns the remaining documents
Query student information starting from Article 2
db.stu.aggregate( {$skip:2} )
3.9 $unwind
Split an array type field in the document into multiple fields, each containing a value in the array
Syntax: db.collection name.aggregate({
u
n
w
i
n
d
:
‘
unwind:’
unwind:’field name’})
db.t2.insert( {_id:1, item:'t-shirt', size:['S', 'M', 'L']} ) db.t2.aggregate( {$unwind:'$size'} ) Note: If the field value containing this array in each document is empty and you want to retain the field content, you can use: db.t2.aggregate( {$unwind:{ path: '$field name', preserveNullAndEmptyArrays:<boolean> # Prevent data loss }} )