当前位置:网站首页>Mongo shell, the most complete mongodb in history

Mongo shell, the most complete mongodb in history

2022-07-07 04:05:00 janyxe

MongoDB List of articles

If this article is helpful to your development path , Please give me a compliment , Your support is my motivation to stick to blogging
Scan the QR code at the bottom of the article to get the e-book and the latest interview materials

Preface

This series of courses will take you in the form of face-to-face test questions Go deep into distributed topics MongoDB. This article takes you in depth MongoDB Shell Use

Mongo Shell Introduce

  • MongoDB Bring their own Javascript Shell, Can be found in Shell Use the command line and MongoDB Real column interaction
  • Mongo Shell from Mozilla Official JavaScript Kernel interpreter , For internal use SpiderMonkey
  • SpiderMonkey Yes ECMA Script Standard compatibility is very good , Support ES 6(ECMA Script 6)

Mongo Shell start-up

Mongo Shell The parameters are as follows

[[email protected] mongodb]# mongo --help
MongoDB shell version v4.4.14
usage: mongo [options] [db address] [file names (ending in .js)]
db address can be:
  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
Options:
  --ipv6                               enable IPv6 support (disabled by 
                                       default)
  --host arg                           server to connect to
  --port arg                           port to connect to
  -h [ --help ]                        show this usage information
  --version                            show version information
  --verbose                            increase verbosity
  --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 ".mongorc.js" file on start up --quiet be less chatty --eval arg evaluate javascript --disableJavaScriptJIT disable the Javascript Just In Time compiler --enableJavaScriptJIT enable the Javascript Just In Time compiler --disableJavaScriptProtection allow automatic JavaScript function marshalling --retryWrites automatically retry write operations upon transient network errors --disableImplicitSessions do not automatically create and use implicit sessions --jsHeapLimitMB arg set the js scope's heap size limit
  --idleSessionTimeout arg (=0)        Terminate the Shell session if it's been
                                       idle for this many seconds

FLE AWS 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 for 
                                       KMS

AWS IAM Options:
  --awsIamSessionToken arg             AWS Session Token for temporary 
                                       credentials

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
  --tlsCRLFile arg                     Certificate Revocation List file for TLS
  --tlsAllowInvalidHostnames           Allow connections to servers with 
                                       non-matching hostnames
  --tlsAllowInvalidCertificates        Allow connections to servers with 
                                       invalid certificates
  --tlsFIPSMode                        Activate FIPS 140-2 mode at startup
  --tlsDisabledProtocols arg           Comma separated list of TLS protocols to
                                       disable [TLS1_0,TLS1_1,TLS1_2]

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
  --gssapiServiceName arg (=mongodb)   Service name to use when authenticating 
                                       using GSSAPI/Kerberos
  --gssapiHostName arg                 Remote host name to use for purpose of 
                                       GSSAPI/Kerberos authentication

file names: a list of files to run. files have to end in .js and will exit after unless --shell is specified
[[email protected] mongodb]# 

The optional parameters are as follows

mongo -u <user> -p <pass> --host <host> --port <port>
Parameters explain
–port Port number , Not specified as default port 27017
-u / -username user name
-p / -password password
-authenticationDatabase Authentication database

Local clients can directly mongo start-up

[[email protected] mongodb]# mongo

Mongo Shell Common commands

Database common commands

show dbs / show databases command

Concept

Show database list

Command application
> show dbs;
admin   0.000GB
config  0.000GB
local   0.000GB

use Database name command

Concept

Switch database , When the database does not exist, it will be created automatically

Command application
> show dbs;
admin   0.000GB
config  0.000GB
local   0.000GB

db.dropDatabase() command

Concept

Delete the collection

Command application
> db.emp.drop()
true
> show collections

Collection common operations

show collections / show tables View set commands

Concept

Query the collection list data of the current database

Command application
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> use test
switched to db test
> db.emp.insert({
    i:1})
WriteResult({
     "nInserted" : 1 })
> show collections
emp

db.collections( Collection name ).stats() View set details command

Concept

View collection details

Command application
> db.emp.stats()
{
    
	"ns" : "test.emp",
	"size" : 33,
	"count" : 1,
	"avgObjSize" : 33,
	"storageSize" : 20480,
	"freeStorageSize" : 0,
	"capped" : false,
	"wiredTiger" : {
    
		"metadata" : {
    
			"formatVersion" : 1
		},
		...
	"scaleFactor" : 1,
	"ok" : 1
}

db.collections( Collection name ).drop() Delete the collection command

Concept

Delete the collection

Command application
> db.emp.drop()
true
> show collections

User role commands

show roles View the role list command

Concept

View role list

Command application
> show roles
{
    
	"role" : "dbAdmin",
	"db" : "test",
	"isBuiltin" : true,
	"roles" : [ ],
	"inheritedRoles" : [ ]
}
{
    
	"role" : "dbOwner",
	"db" : "test",
	"isBuiltin" : true,
	"roles" : [ ],
	"inheritedRoles" : [ ]
}
{
    
	"role" : "enableSharding",
	"db" : "test",
	"isBuiltin" : true,
	"roles" : [ ],
	"inheritedRoles" : [ ]
}
{
    
	"role" : "read",
	"db" : "test",
	"isBuiltin" : true,
	"roles" : [ ],
	"inheritedRoles" : [ ]
}
{
    
	"role" : "readWrite",
	"db" : "test",
	"isBuiltin" : true,
	"roles" : [ ],
	"inheritedRoles" : [ ]
}
{
    
	"role" : "userAdmin",
	"db" : "test",
	"isBuiltin" : true,
	"roles" : [ ],
	"inheritedRoles" : [ ]
}

db.createUser( User information ) Create user command

Concept

Create user

Command format

db.createUser({user:“ user name ”,pwd:“ name ”,roles:[“ role ”]})

Command parameter meaning
user User name
pwd password
roles Character list
Command application

establish test library , And designate test The administrator of the library

> use test
switched to db test
> dn.createUser({
    user:"test",pwd:"test",roles:['dbOwner']})
uncaught exception: ReferenceError: dn is not defined :
@(shell):1:1
> use test
switched to db test
> db.createUser({
    user:"test",pwd:"test",roles:['dbOwner']})
Successfully added user: {
     "user" : "test", "roles" : [ "dbOwner" ] }
> show users
{
    
	"_id" : "test.test",
	"userId" : UUID("d9be5de9-8c28-4b2b-8d88-530be7846b14"),
	"user" : "test",
	"db" : "test",
	"roles" : [
		{
    
			"role" : "dbOwner",
			"db" : "test"
		}
	],
	"mechanisms" : [
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	]
}
> 

db.dropUser( User name ) Delete user command

Concept

Create user

Command format

db.dropUser(“ user name ”)

Command application

db.dropUser(“test”)

> use test
switched to db test
> dn.createUser({
    user:"test",pwd:"test",roles:['dbOwner']})
uncaught exception: ReferenceError: dn is not defined :
@(shell):1:1
> use test
switched to db test
> db.createUser({
    user:"test",pwd:"test",roles:['dbOwner']})
Successfully added user: {
     "user" : "test", "roles" : [ "dbOwner" ] }
> show users
{
    
	"_id" : "test.test",
	"userId" : UUID("d9be5de9-8c28-4b2b-8d88-530be7846b14"),
	"user" : "test",
	"db" : "test",
	"roles" : [
		{
    
			"role" : "dbOwner",
			"db" : "test"
		}
	],
	"mechanisms" : [
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	]
}
> 

to see somebody for the first time , I don't know what to give you . Simply send hundreds of e-books and the latest interview materials , I wish you a better job , Scan the QR code below to get

原网站

版权声明
本文为[janyxe]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207062129302157.html