Introduce a,

MongoDB is a database based on distributed file storage. Written in C++ language. Designed to provide scalable high-performance data storage solutions for WEB applications. MongoDB is a product between relational database and non-relational database. Among non-relational databases, it has the most rich functions and is the most like relational database. The data structure it supports is very loose, in jSON-like Bson format, so it can store more complex data types. The biggest feature of Mongo is that the query language it supports is very powerful. Its syntax is somewhat similar to object-oriented query language. It can almost achieve most of the functions similar to single table query of relational database, and it also supports data indexing. It is characterized by high performance, easy deployment, easy use, and very convenient data storage.

The main features are:

MongoDB is a standalone server; It’s document-based, not table-based; It’s unstructured; It has strong support for major development languages such as C#, C++, Java, PHP, Perl, Python, Ruby. Scalability uses efficient binary data storage, including large objects (such as videos). Full index support, including internal objects. Collective-oriented storage, easy to store object type data.

2. Basic concepts of mongodb

Document: the basic unit of data in MongoDB, much like rows (but much more complex) in relational database systems: A set of documents. If documents in MongoDB are like rows in a relational database, collections are like tables. A single computer in MongoDB can hold multiple independent databases, and each database has its own collections and permissions. This tool is very useful for managing MongoDB instances and manipulating databases. Each document has a special key “_id”, which is unique in the collection of documents and is equivalent to the primary key of a table in a relational database

Third, MongoDB data type

4. Common commands

1. Common basic operations

Show DBS: Displays the database list. Db: view the current database. db.createCollection('Name of table to be created'Create a new table; Show collections: view tables under the current database; DropDatabase () : delete the current database show users: view all users of the current database db.dropdatabase () : Db.clonedatabase (" 127.0.0.1 ") : Clone the data of the database on the specified machine to the current database db.copyDatabase("mydb"."temp"."127.0.0.1"RepairDatabase () : Repairs the current database db.getName() : views the currently used database db.stats() : Displays the current DB status db.version() : Current DB version db.getmongo () : view the IP address of the connected machine of the current DB. Db.serverstatus ().connections.current: View the current number of connectionsCopy the code

A Collection of books

Db.createcollection (" collName ", {size: 20, capped: 5, Max: 100}); Create an aggregate collection (table) db.getCollection("account"); Get the collection (table) db.getCollectionNames(); Db.printcollectionstats (); Displays the status of all clustered indexes in db# check the basic information of the aggregate collection1, Check the help db.yourcol.help (); Db.yourcol.count (); Db.userinfo.datasize (); Db.userinfo.getdb (); Db.userinfo.stats (); Db.userinfo.totalsize (); Db.userinfo.storagesize (); 8, Shard version information db. The userInfo. GetShardVersion () 9, gathered a collection rename the db. The userInfo. RenameCollection ("users"); Drop (db.userinfo.drop (); drop(db.userinfo.drop ()); drop(db.userinfo.drop ());Copy the code

3. Add, delete, modify and check data

# increase:1, insert a data db. Db. Test1. InsertOne (data);#insertOne can only insert 1 dataInsert ([data_1, data_2]); insert(data_1, data_2); Db. Table name. InsertMany ([data 1, data 2]); Save db. Table name. Save (data); Insert differs from save: If the default value of "_id" already exists, an error will be reported when you call insert. The save method does not update the information for the same _id row# deleteDb. Table name. Remove (condition);Delete only the data that meets the criteria in the first column by defaultDb. Table name. DeleteOne (condition)Delete all data that meets the criteriaDb. Table name. DeleteMany (condition)# changeThe name of the table. The update ({"Condition field name":"Field value"}, {$set: {"Name of field to be modified":"Modified field value"}});
 
# Change a data updateOne
db.inventory.updateOne(
   { item: "paper" },
   {
     $set: { "size.uom": "cm", status: "P" },
     $currentDate: { lastModified: true}})Modify multiple data updateMany
db.inventory.updateMany(
   { "qty": { $lt: 50}}, {$set: { "size.uom": "in", status: "P" },
     $currentDate: { lastModified: true}})# replace replaceOne
db.inventory.replaceOne(
   { item: "paper" },
   { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
)
 
# checkTable name find(): queries all data in a table db. table name find(condition): queries db based on conditions Table name findOne(Conditional): Queries the first DB (supported). Table name.find ().limit: limit the number of pages in db. Table name.find ().skip(number): skip the specified number db.table name.find ().skip(number).limit(number of items to display): for example, display 10 items starting from 10Copy the code

4, db.serverStatus() details

PRIMARY> db.serverStatus()
{
"host" : "cd9a511a2d0e".# the hostname
"version" : "2.6.1".# version number
"process" : "mongod".# process name
"pid" : NumberLong(41), # process ID
"uptime" : 3785943,  # run time
"uptimeMillis" : NumberLong("3785942955"),
"uptimeEstimate" : 3755878,
"localTime" : ISODate("The 2015-10-16 T02: but 368 z"),  # current time
"asserts" : {  # Number of individual assertions
"regular": 0."warning": 0."msg": 0."user": 58."rollovers": 0}."backgroundFlushing" : {
"flushes" : 63098,  # refresh times
"total_ms" : 144997713,  # Total time to refresh
"average_ms": 2297.97637009097.# Average time
"last_ms" : 10913,  # Last time
"last_finished" : ISODate("The 2015-10-16 T02:45:40:15. 363 z")  # last refresh time
},
"connections" : {
"current" : 1444,  # Number of current connections
"available" : 18556,  # Number of available connections
"totalCreated" : NumberLong(2429949)
},
"cursors" : {
"note" : "deprecated, use server status metrics"."clientCursors_size" : 1,  Client cursor size
"totalOpen" : 1,  Open the cursor count
"pinned": 0."totalNoTimeout" : 481,
"timedOut" : 84  # timeout
},
"dur" : {
"commits" : 27,
"journaledMB": 2.711552."writeToDataFilesMB": 5.213888."compression": 0.5158220112430492."commitsInWriteLock": 0."earlyCommits": 0."timeMs" : {
"dt" : 3003,
"prepLogBuffer" : 1,
"writeToJournal" : 228,
"writeToDataFiles" : 10,
"remapPrivateView": 2}},"extra_info" : {
"note" : "fields vary by platform"."heap_usage_bytes" : 96529464,  # Heap usage (bytes)
"page_faults" : 11253067  # Number of page failures
},
"globalLock" : {
"totalTime" : NumberLong("3785942955000"),
"lockTime" : NumberLong("47441423960"),
"currentQueue" : {
"total": 0."readers": 0."writers": 0}."activeClients" : {
"total": 0."readers": 0."writers": 0}},"indexCounters" : {
"accesses" : 5980339643,  # index number of accesses
"hits" : 5980339322,  Number of index hits
"misses": 0.Number of index deviations
"resets": 0.# reset number
"mi***atio" : 0  # Missed percentage
},
"locks" : {
"." : {
"timeLockedMicros" : {
"R" : NumberLong(1300731481),
"W" : NumberLong("47441423960")},"timeAcquiringMicros" : {
"R" : NumberLong("83350794378"),
"W" : NumberLong("8842280365")}}},"network" : {
"bytesIn" : 182494603618,  # Input data (byte)
"bytesOut" : NumberLong("2936449550300"),  Output data (byte)
"numRequests" : 600302443 # number of requests
},
"opcounters" : {
"insert" : 214538892,  Insert operands
"query" : 388689,  Query operands
"update" : 3462611, Update operands
"delete": 0,,Delete operands
"getmore" : 188590632,  Get more operands
"command" : 197825527  Other command operands
},
"opcountersRepl" : {
"insert" : 1,
"query": 0."update": 0."delete": 0."getmore": 0."command": 0}."recordStats" : {
"accessesNotInMemory" : 8377141,
"pageFaultExceptionsThrown" : 2926497,
"admin" : {
"accessesNotInMemory" : 94,
"pageFaultExceptionsThrown": 0}},"repl" : {  # Replication status
"setName" : "c562ca6c-1d72-4c6a-a943-b46fe87e47ca"."setVersion" : 105039,
"ismaster" : true."secondary" : false."hosts" : [
"10.10.1.1:27017"."10.10.1.2:27017"]."arbiters" : [
"10.10.1.2:27017"]."primary" : "10.10.1.4:27017"."me" : "10.10.1.5:27017"
},
"writeBacksQueued" : false."mem" : {  # Memory condition
"bits" : 64,  # 64-bit operating system
"resident" : 4430,  Number of physical memory occupied
"virtual" : 813370,  Number of virtual memory occupied
"supported" : true.Whether memory expansion is supported
"mapped" : 405498,
"mappedWithJournal": 810996}."metrics" : {
"cursor" : {
"timedOut" : NumberLong(84),
"open" : {
"noTimeout" : NumberLong(481),
"pinned" : NumberLong(0),
"total" : NumberLong(1)
}
},
"document" : {
"deleted" : NumberLong(0),
"inserted" : NumberLong(214538892),
"returned" : NumberLong("6735629965"),
"updated" : NumberLong(6502807)
},
"getLastError" : {
"wtime" : {
"num": 0."totalMillis": 0}."wtimeouts" : NumberLong(0)
},
"operation" : {
"fastmod" : NumberLong(3483995),
"idhack" : NumberLong(39),
"scanAndOrder" : NumberLong(6)
},
"queryExecutor" : {
"scanned" : NumberLong(107218344),
"scannedObjects" : NumberLong(107217952)
},
"record" : {
"moves" : NumberLong(1604)
},
"repl" : {
"apply" : {
"batches" : {
"num": 2."totalMillis": 8},"ops" : NumberLong(1)
},
"buffer" : {
"count" : NumberLong(0),
"maxSizeBytes" : 268435456,
"sizeBytes" : NumberLong(0)
},
"network" : {
"bytes" : NumberLong(709),
"getmores" : {
"num": 18."totalMillis": 86108}."ops" : NumberLong(2),
"readersCreated" : NumberLong(35)
},
"preload" : {
"docs" : {
"num": 0."totalMillis": 0}."indexes" : {
"num" : 1,
"totalMillis": 0}}},"storage" : {
"freelist" : {
"search" : {
"bucketExhausted" : NumberLong(0),
"requests" : NumberLong(6551285),
"scanned" : NumberLong(12001208)
}
}
},
"ttl" : {
"deletedDocuments" : NumberLong(0),
"passes" : NumberLong(63048)
}
},
"ok": 1}Copy the code

5. Permission management

1. Mongodb database user roles

Database user roles
read: allows the user to read the specified databasereadWrite: Allows users to read and Write the specified databaseDatabase administrator roleDbAdmin: allows users to create and delete indexes, view statistics, or access system.profile, but does not have the rights to manage roles and users. UserAdmin: Allows users to create and modify roles and users in the current database. The roles come togetherreadPrivileges granted by Write, dbAdmin, and userAdmin roles.# Cluster management roleClusterAdmin: Provides the most powerful cluster management access. Ability to combine clusterManager, clusterMonitor, and hostManager roles. The dropDatabase operation clusterManager is also provided: provides administrative and monitoring operations on the cluster. Access to configuration and local databases used for sharding and replication clusterMonitor, respectively: provides read-only access to monitoring tools such as the MongoDB cloud manager and Ops Manager monitoring agent. HostManager: Provides the ability to monitor and manage servers.Backup and restore rolesBackup: provides the capabilities required to backup data using MongoDB cloud manager backup proxy, Ops manager backup proxy, or mongodump restore: provides the capabilities required to restore data using mongorestoreAll database roles
readAnyDatabase: the AnyDatabase is available only in the admin database and is granted the read permission of all databasesreadWriteAnyDatabase: Only available in the admin database, granting the user read and write permissions for all databases userAdminAnyDatabase: DbAdminAnyDatabase: This parameter is available only in the admin database and is granted to the user with the dbAdmin permission for all databases.# Superuser roleRoot: YesreadAccess to all resources of WriteAnyDatabase, dbAdminAnyDatabase, userAdminAnyDatabase, clusterAdmin, Restore, and BackupCopy the code

2. Create a user

Create a super administrator
use admin
db.createUser({
    user:"admin".pwd:"123456",
    roles:[{
        role:"root",
        db:"admin"}]})Create a normal user
Create user testDB (123456) with readWrite permission
use testDB Enter the testDB database
db.createUser({user:'test'.pwd:'123456',roles:[{role:'readWrite',db:'testDB'}]})
 
# change password
db.updateUser('test',{user:'test'.pwd:'admin',roles:[{role:'read',db:'testDB'}]}) // Change the password and // change the role to read-onlyCopy the code

3. Common user commands

Add a user
db.addUser("name");
db.addUser("userName"."pwd123".true); Add a user, set a password, and check whether the user is read-only# Database authentication, security mode
db.auth("userName"."123123");
 
# View all users
 show users;
# delete user
 db.removeUser("test")
Copy the code

Six, index,

Db.userinfo.ensureindex ({name: 1}); db.userInfo.ensureIndex({name: 1, ts: -1}); Db.userinfo.getindexes (); 3, check the total index record size db. The userInfo. TotalIndexSize (); Db.users.reindex (); db.users.reindex (); Drop db.users.dropindex (db.users.dropindex)"name_1"); Db.users.dropindexes ();Copy the code

7. Security Reinforcement

  • 1. Run mongodb as a common user without using root
  • 2. Specify bind_IP (do not use 0.0.0.0)
  • 3, Use login authentication (auth = true)
  • 4. Mongodb ports are not allowed to be opened to the public

Configure systemcal to start mongodb

#1. View configuration files
[root@localhost  ~]# cat /usr/local/mongodb/conf/mongodb.conf
# Directory for storing data files
dbpath = /data/mongodata
# Directory for storing log files
logpath = /data/logs/mongolog/mongodb.log
# port
port = 27017
# daemon enabled, that is, run in the background
fork = true
# to monitor IPBind_ip = 127.0.0.1# Maximum number of connections
maxConns=65536
# pid file
pidfilepath=/var/run/mongo/mongod.pid
# enable authentication
#auth = true
 
#2 create a mongo account
useradd -s /sbin/nologin  -M mongo
 
Create directory and license
mkdir -p /data/mongodata
mkdir -p /data/logs/mongolog
mkdir -p /var/run/mongo
chown -R /data/mongodata
chown -R /data/logs/mongolog
chown -R /var/run/mongo
 
#service configuration file
[root@localhost  ~]# cat /usr/lib/systemd/system/mongodb.service
[Unit]
Description=mongodb
After=network.target
  
[Service]
Type=forking
PIDFile=/var/run/mongo/mongod.pid
ExecStart=/usr/local/mongodb/bin/mongod -f /usr/local/mongodb/conf/mongodb.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
 
 
User=mongo
Group=mongo
 
  
[Install]
WantedBy=multi-user.target
Copy the code