Theoretical basis, installation and basic operation of NoSQL
Starting in 30 minutes.
Distributed system theory:
CAP:
Consistency
Usability
Partition fault tolerance
MongoDB:
Installation
Crud
Indexes
Replica set
Slice
NoSQL: non-relational, distributed, does not provide ACID functionality
Technical features:
1. Simple data model
2. Separation of metadata and application data (stored on different servers)
3. Weak consistency
Advantages:
1. Avoid unnecessary complexity
2. High throughput
3. High-level scalability and low-end hardware cluster
4. Object-relational mapping is not applicable
Disadvantages:
1. ACID feature is not supported
2. Simple function
3. There is no unified data query model.
Classification:
NoSQL:
Key value storage
Column database
Document database
Schema database
SQL:
Mysql
Pgsql
Cache database system:
Memcache
CAP Theory: pick 2 from CAP
BASE theory:
Basic availability
Soft state
Final consistency
Cperfine Aazzo SQL (ensure consistency, availability)
C _ journal P: pessimistic locking mechanism (consistency, partition fault tolerance)
A,P:DNS
Data consistency model: strong consistency, weak consistency, final consistency
The realization technology of data consistency:
Quorum (legal number of votes) system NRW policy (concern)
N: number of copies
R: the minimum number of copies required to complete the read operation
W: the minimum number of copies required to complete the write operation
To ensure strong consistency: ringing W > N
At best, the ultimate consistency can only be guaranteed: rang W db.helpfunction () {print ("DB methods:"); print ("\ tdb.addUser (userDocument)"); print ("\ tdb.adminCommand (nameOrDocument)-switches to 'admin' db, and runs command [just calls db.runCommand (...)]"); print ("\ tdb.auth (username, password)"); print ("\ tdb.cloneDatabase (fromhost)") Print ("\ tdb.commandHelp (name) returns the help for the command"); print ("\ tdb.copyDatabase (fromdb, todb, fromhost)"); print ("\ tdb.createCollection (name, {size:..., capped:..., max:...})"); print ("\ tdb.currentOp () displays currently executing operations in the db"); print ("\ tdb.dropDatabase ()") Print ("\ tdb.eval (func, args) run code server-side"); print ("\ tdb.fsyncLock () flush data to disk and lock server for backups"); print ("\ tdb.fsyncUnlock () unlocks server following a db.fsyncLock ()"); print ("\ tdb.getCollection (cname) same as db ['cname'] or db.cname"); print ("\ tdb.getCollectionNames ()"); print ("\ tdb.getLastError ()-just returns the err msg string") Print ("\ tdb.getLastErrorObj ()-return full status object"); print ("\ tdb.getMongo () get the server connection object"); print ("\ tdb.getMongo (). SetSlaveOk () allow queries on a replication slave server"); print ("\ tdb.getName ()"); print ("\ tdb.getPrevError ()"); print ("\ tdb.getProfilingLevel ()-deprecated") Print ("\ tdb.getProfilingStatus ()-returns if profiling is on and slow threshold"); print ("\ tdb.getReplicationInfo ()"); print ("\ tdb.getSiblingDB (name) get the db at the same server as this one"); print ("\ tdb.hostInfo () get details about the server's host"); print ("\ tdb.isMaster () check replica primary status"); print ("\ tdb.killOp (opid) kills the current operation in the db") Print ("\ tdb.listCommands () lists all the db commands"); print ("\ tdb.loadServerScripts () loads all the scripts in db.system.js"); print ("\ tdb.logout ()"); print ("\ tdb.printCollectionStats ()"); print ("\ tdb.printReplicationInfo ()"); print ("\ tdb.printShardingStatus ()"); print ("\ tdb.printSlaveReplicationInfo ()"); print ("\ tdb.removeUser (username)") Print ("\ tdb.repairDatabase ()"); print ("\ tdb.resetError ()"); print ("\ tdb.runCommand (cmdObj) run a database command. If cmdObj is a string, turns it into {cmdObj: 1} "); print ("\ tdb.serverStatus () "); print ("\ tdb.setProfilingLevel (level,) 0=off 1=slow 2=all "); print ("\ tdb.setVerboseShell (flag) display extra information in shell output "); print ("\ tdb.shutdownServer () "); print ("\ tdb.stats () "); print ("\ tdb.version () current version of the server "); return _ magicNoPrint;}
Collection help:
> db.mycoll.help () DBCollection help db.mycoll.find (). Help ()-show DBCursor help db.mycoll.count () db.mycoll.copyTo (newColl)-duplicates collection by copying all documents to newColl; no indexes are copied. Db.mycoll.convertToCapped (maxBytes)-calls {convertToCapped:'mycoll' Size:maxBytes}} command db.mycoll.dataSize () db.mycoll.distinct (key)-e.g. Db.mycoll.distinct ('x') db.mycoll.drop () drop the collection db.mycoll.dropIndex (index)-e.g. Db.mycoll.dropIndex ("indexName") or db.mycoll.dropIndex ({"indexKey": 1}) db.mycoll.dropIndexes () db.mycoll.ensureIndex (keypattern [ Options])-options is an object with these possible fields: name, unique, dropDups db.mycoll.reIndex () db.mycoll.find ([query], [fields])-query is an optional query filter. Fields is optional set of fields to return. E.g. Db.mycoll.find ({name:1, x db.mycoll.find 1}) db.mycoll.find (...). Count () db.mycoll.find (...). Limit (n) db.mycoll.find (...). Skip (n) db.mycoll.find (...). Sort (...) Db.mycoll.findOne ([query]) db.mycoll.findAndModify ({update:..., remove: bool [, query: {}, sort: {}, 'new': false]}) db.mycoll.getDB () getDB object associated with collection db.mycoll.getIndexes () db.mycoll.group ({key:..., initial:..., reduce:. [ Cond:...]}) db.mycoll.insert (obj) db.mycoll.mapReduce (mapFunction, reduceFunction,) db.mycoll.remove (query) db.mycoll.renameCollection (newName,) renames the collection. Db.mycoll.runCommand (name,) runs a db command with the given name where the first param is the collection name db.mycoll.save (obj) db.mycoll.stats () db.mycoll.storageSize ()-includes free space allocated to this collection db.mycoll.totalIndexSize ()-size in bytes of all the indexes db.mycoll.totalSize ()-storage allocated for all data and indexes db.mycoll.update (query, object [, upsert_bool, multi_bool])-instead of two flags You can pass an object with fields: upsert, multi db.mycoll.validate ()-SLOW db.mycoll.getShardVersion ()-only for use with sharding db.mycoll.getShardDistribution ()-prints statistics about data distribution in the cluster db.mycoll.getSplitKeysForChunks ()-calculates split points over all chunks and returns splitter function
Easy to use:
Using a database: (no need to create), and no need for collection to create
Db.collection.insert: insertin
Show collections: query collection
Db.collections.find (): query statement
Db.collections.update (): update
Db.collections.remove (): removin
Collection information:
Delete the collection:
View the database file:
Basic operations:
Show dbs: view all databases
Show collections: viewing collections
Show users: viewing users
Show profile:
Show logs: view a list of all logs
Show log [name]: view specific logs
Remote connection:
Mongo-host ip
Crud operation:
Create,read,update,delete
Although there is no table structure, you should put a collection for similar objects.
Query:
Db.users.find ({age: {$gt:18}}) .sort ({age:1}) query users whose age is greater than 18, and sort them in ascending order of age
Insert:
Db.users.insert (
{
Name:'suse'
Age:26
Status:'A'
Group: ['news','sports']
}
)
Update:
Db.coll.update (
{age: {$gt:18}}
{$set: {status:'A'}}
{multi:true} modify only the first eligible one when it is not specified
)
Delete:
Db.coll.delete (
{status:'D'}
)
Insert:
Only 20 are displayed in a batch. Enter it to continue.
Limit:
Delete:
Modify:
Advanced usage of find:
Db.collection.find (,)
Db.collection.count () returns the number of entries
Comparison operation:
$gt: greater than {field: {$gt:value}}
$gte: greater than or equal to {field: {$gte:value}}
$in: exists in {field: {$in: [value1,value2,...]}}
$lt: less than {field: {$lt:value}}
Lte: less than or equal to {field: {$lte:value}}
$ne: not equal to {field: {$ne:value}}
$nin: does not exist in {field: {$nin: [value1,value2...]}}
Greater than
Display the required fields:
Logical operation:
$or: or operation, {$or: [{expression1}, {expression2},...]}
$and: or operation, {$and: [{expression1}, {expression2},...]}
$not: or operation, {field: {$not: {operator-expression}
$nor: inverse operation, that is, returns documents that do not meet all the specified conditions, {$nor: [{expression1}, {expression2},...]}
And operation:
Element query:
If you want to select a document under conditions such as whether there is a field in the separated document, you need to use element operations.
$exists: selects documents according to the existence of the specified field. Syntax: {field: {$exists:}}. The specified value is' true''to return the document with the specified field, and 'false' to return the document without the specified field
$mod: a document in which the value of the specified field is modular and the rest is returned as the specified value. Syntax {field: {$mod: [divisor,remainder]}}
$type: returns the document whose value type of the specified field is the specified type. Syntax: {field: {$type:}}
Reinsert a piece of data:
Query:
Update:
The update proprietary operator roughly consists of: field,array,bitwise
Field:
$inc: increase the value of the specified field. Format:
Db.collection.update ({field:value}, {$nic: {field1:amount}}), where {field:value} is used to specify the selection criteria, and {$inc: {field1:amount}} is used to specify the field whose value is to be raised and the size of the amount
$rename: change the field name in the format {$rename: {:,:,...}}
$set: modify the value of the field to the newly specified value in the format db.collection.update ({field:value1}, {$set: {field2:value2}})
$unset: deletes the specified field in the format db.collection.update ({field:value1}, {$unset: {field1: ""}})