MongoDB database Overview
MongoDB is a high-performance, open-source, and non-pattern document-type database. It can be used in many scenarios to replace the traditional relational database or key/value storage mode. MongoDB is developed in C ++ and provides the following functions:
- Set-oriented storage: Suitable for storing objects and JSON data.
- Dynamic query: Mongo supports multiple Query expressions. Query commands use JSON tags to easily query embedded objects and arrays in a document.
- Complete indexing support: Includes embedded object and array of documents. The Query Optimizer of Mongo analyzes the query expression and generates an efficient query plan.
- Query monitoring: Mongo provides a monitoring tool to analyze the performance of database operations.
- Replication and automatic failover: The Mongo Database supports data replication between servers and master-slave mode and inter-Server replication. The primary objective of replication is to provide redundancy and auto failover.
- Efficient traditional storage: supports binary data and large objects (such as photos or images ).
- Automatic sharding to support cloud-level Scalability (in the early Alpha stage): the automatic sharding function supports horizontal database clusters and allows you to dynamically add additional machines.
MongoDB's main goal is to build a bridge between key/value storage (providing high performance and high scalability) and traditional RDBMS systems (rich functions, set the advantages of both. Mongo is applicable to the following scenarios:
- Website data: Mongo is ideal for real-time insertion, update, and query, as well as the replication and high scalability required for real-time website data storage.
- Cache: because of its high performance, Mongo is also suitable for serving as a cache layer for information infrastructure. After the system is restarted, the persistent cache layer established by Mongo can avoid data source overload at the lower layer.
- Large-sized and low-value data: traditional relational databases may be expensive to store some data. Previously, programmers often choose traditional files for storage.
- High scalability: Mongo is ideal for databases consisting of dozens or hundreds of servers. The Mongo roadmap contains built-in support for the mapreduce engine.
- For object and JSON Data Storage: Mongo's bson data format is very suitable for storing and querying document-based data.
Naturally, there are some restrictions on the use of MongoDB, for example, it is not suitable:
- A highly transactional system, such as a banking or accounting system. Traditional relational databases are still more suitable for applications that require a large number of atomic complex transactions.
- Traditional Business Intelligence applications: Bi databases for specific problems will produce highly optimized query methods. For such applications, data warehouse may be a more appropriate choice.
- SQL Problems
MongoDB supports OS X, Linux, windows, and other operating systems. It provides drivers for python, PHP, Ruby, Java, C, C #, JavaScript, Perl, and C ++, the Erlang and. net and other platform drivers
Usage:
Log on to MongoDB using the Mongo client program
- Falcon@www.fwphp.cn ~ /MongoDB] $ bin/Mongo
- MongoDB shell version: 1.2.4-
- URL: Test
- Connecting to: Test
- Type "help" for help
- > Help
- Help
- Show DBS show Database Name
- Show collections shows the collection of the current database
- Show users
- Show profile: displays the system overview with the last system time greater than 1 ms
- Use <dB Name> switch to database
- DB. Help () Help on DB Methods
- DB. Foo. Help () Help on collection methods
- DB. Foo. Find () List objects in collection foo
- DB. Foo. Find ({A: 1}) List objects in Foo where a = 1
- It result of the last line evaluated; use to further iterate
- > Show DBS has two databases by default.
- Admin
- Local
- > Switch use admin to the admin database.
- Switched to DB Admin
- > Show collections: displays the collection below the admin Database
- System. Indexes
Next we will simply create a collection, insert, update, and query data to experience the different things MongoDB brings to us.
The method for creating a database is in
Create a collection:
- > DB. createcollection ("user ");
- {"OK": 1}
- > Show collections
- System. Indexes
- User
- >
Insert data:
- > DB. User. insert ({uid: 1, Username: "falcon. c", age: 25 });
- > DB. User. insert ({uid: 2, Username: "AABC", age: 24 });
Query data:
- > DB. User. Find ();
- {"_ Id": objectid ("4b81e74c1f0fd3b9545cba43"), "uid": 1, "username": "falcon. c", "Age": 25}
- {"_ Id": objectid ("4b81e74d1f0fd3b9545cba44"), "uid": 2, "username": "AABC", "Age": 24}
You can query data in a variety of ways. SQL-like conditional queries will be detailed in future documents.
For example, I want to query user information with UID 1.
- > DB. User. Find ({uid: 1 });
- {"_ Id": objectid ("4b81e74c1f0fd3b9545cba43"), "uid": 1, "username": "falcon. c", "Age": 25}
Among others, there are a wide range of queries including limit, sort, findone, and distinct.
Update Data:
- > DB. User. Update ({uid: 1}, {$ set: {age: 26 }})
- > DB. User. Find ();
- {"_ Id": objectid ("4b81e76f1f0fd3b9545cba45"), "uid": 1, "username": "falcon. c", "Age": 26}
- {"_ Id": objectid ("4b81e7701f0fd3b9545cba46"), "uid": 2, "username": "AABC", "Age": 24}
- > DB. User. Update ({uid: 1}, {$ Inc: {age:-1 }})
- > DB. User. Find ();
- {"_ Id": objectid ("4b81e76f1f0fd3b9545cba45"), "uid": 1, "username": "falcon. c", "Age": 25}
- {"_ Id": objectid ("4b81e7701f0fd3b9545cba46"), "uid": 2, "username": "AABC", "Age": 24}
- >
The above two usage methods are provided. The update conditions include $ unset, $ push, $ pushall, $ pop, $ pull, and $ pullall.
The above is a brief introduction to MongoDB usage. In future documents, we will introduce in detail MongoDB's cool curd method, MongoDB's replication and distribution.
MongoDB usage skills
If you want to view which database is connected, you can directly enter the database
- > DB
- Admin
Want to switch to the Test Database
- > Use test
- Switched to DB Test
- > DB
- Test
You can enter
- > Show collections
- System. Indexes
- User
If you want to know which commands MongoDB supports, you can directly enter help
- > Help
- Help
- Show DBS show database names
- Show collections show collections in current database
- Show users show users in current database
- Show profile show most recent system. Profile entries with time> = 1 ms
- Use <dB Name> set curent database to <dB Name>
- DB. Help () Help on DB Methods
- DB. Foo. Help () Help on collection methods
- DB. Foo. Find () List objects in collection foo
- DB. Foo. Find ({A: 1}) List objects in Foo where a = 1
- It result of the last line evaluated; use to further iterate
If you want to know the methods supported by the current database:
- > DB. Help ();
- DB methods:
- DB. adduser (username, password) add authorized database users
- DB. Auth (username, password) access authentication
- DB. clonedatabase (fromhost) clone Database
- DB. commandhelp (name) returns the help for the command
- DB. copydatabase (fromdb, todb, fromhost)
- DB. createcollection (name, {size:..., capped:..., Max:...}) create a table
- DB. currentop () displays the current operation in the DB
- DB. dropdatabase () Delete the current database
- DB. eval (func, argS) run code server-side
- DB. getcollection (cname) Same As DB ['cname'] or db. cname
- DB. getcollectionnames () Get the table name of the current database
- DB. getlasterror ()-Just returns the err MSG string
- DB. getlasterrobj ()-return full status object
- DB. getmongo () Get the server connection object
- DB. getmongo (). setslaveok () allow this connection to read from the nonmaster member of a replica pair
- DB. getname ()
- DB. getpreverror ()
- DB. getprofilinglevel ()
- DB. getreplicationinfo ()
- DB. getsisterdb (name) Get the dB at the same server as this onew
- DB. Killop () kills the current operation in the DB
- DB. printcollectionstats () prints the status information of each table
- DB. printreplicationinfo () prints the replication status of the primary database.
- DB. printslavereplicationinfo () prints the copy status information from the database
- DB. printshardingstatus () prints the shard status information
- DB. removeuser (username) delete database users
- DB. repairdatabase () repair Database
- DB. reseterror ()
- DB. runcommand (cmdobj) run a database command. If cmdobj is a string, turns it into {cmdobj: 1}
- DB. setprofilinglevel (level) 0 = off 1 = slow 2 = all
- DB. shutdownserver ()
- DB. Version () Current version of the server
If you want to know the methods supported by tables or table collections in the current database, you can run the following command:
- > DB. User. Help (); User indicates the table name.
- Dbcollection help
- Number of rows in the DB. Foo. Count () Statistical table
- DB. Foo. datasize () statistics table data size
- DB. Foo. Distinct (key)-eg. DB. Foo. Distinct ('x') Division by given conditions
- DB. Foo. Drop () Drop the collection to delete a table
- DB. Foo. dropindex (name) deletes the specified index
- DB. Foo. dropindexes () Delete All indexes
- DB. Foo. ensureindex (keypattern, options)-options shocould be an object with these possible fields: name, unique, and dropdups add Indexes
- DB. Foo. Find ([query], [fields])-First parameter is an optional query filter. Second parameter is optional set of fields to return. query data based on conditions
- E.g. DB. Foo. Find ({X: 77}, {Name: 1, x: 1 })
- DB. Foo. Find (...). Count ()
- DB. Foo. Find (...). Limit (n) searches for data based on conditions and returns the specified number of records.
- DB. Foo. Find (...). Skip (N)
- DB. Foo. Find (...). Sort (...) Search for sorting
- DB. Foo. findone ([query]) queries only one data record by condition
- DB. Foo. getdb () Get dB object associated with collection returns the database to which the table belongs.
- DB. Foo. getindexes () displays all indexes of the table.
- DB. Foo. Group ({key:..., initial:..., reduce:... [, Cond:...]}) grouped by conditions
- DB. Foo. mapreduce (mapfunction, performancefunction, <optional Params>)
- DB. Foo. Remove (query) delete data based on conditions
- DB. Foo. renamecollection (newname) renames the collection to rename the table
- DB. Foo. Save (OBJ) save data
- DB. Foo. Stats () view the table status
- DB. Foo. storagesize ()-distributed des free space allocated to this collection query allocated to the tablespace size
- DB. Foo. totalindexsize ()-size in bytes of all the indexes query the size of all indexes
- DB. Foo. totalsize ()-storage allocated for all data and Indexes
- DB. Foo. Update (query, object [, upsert_bool]) updates data based on conditions.
- DB. Foo. Validate ()-slow verification table details
- DB. Foo. getshardversion ()-only for use with sharding
MongoDB backup tool mongodump
If you want to back up the database test, for example:
- [Falcon@www.fwphp. CN ~ /MongoDB/bin] $./mongodump -- Help
- Options:
- -- Help produce help message
- -H [-- Host] Arg Mongo host to connect
- -D [-- dB] Arg database to use
- -C [-- collection] Arg collection to use (some commands)
- -U [-- username] Arg Username
- -P [-- Password] Arg Password
- -- Dbpath Arg directly access your D data files in this path,
- Instead of connecting to a mongod instance
- -V [-- verbose] Be more verbose (include multiple times for more
- Verbosity e.g.-vvvvv)
- -O [-- Out] Arg (= dump) output directory
- Falcon@www.fwphp.cn ~ /MongoDB/bin] $ [color = Blue]./mongodump-d test-O test/[/color]
- Connected to: 127.0.0.1
- Database: Test to test/test
- Test. User to test/user. bson
- 100000 objects
- Test. system. indexes to test/system. Indexes. bson
- 1 objects
- Falcon@www.fwphp.cn ~ /MongoDB/bin] $ ls
- 2 Mongo mongodump program files mongorestore mongosniff
- Dump mongod export Export Import mongos Test
MongoDB data recovery tool mongorestore
View tables in the Test Database
- > Show collections
- System. Indexes
- User
Delete user table
- > DB. User. Drop ();
- True
- > Show collections
- System. Indexes
Now, the mongorestore table is used to restore the data backed up by mongodump.
- Falcon@www.fwphp.cn ~ /MongoDB/bin] $./mongorestore -- Help
- Usage:./mongorestore [Options] [directory or filename to restore from]
- Options:
- -- Help produce help message
- -H [-- Host] Arg Mongo host to connect
- -D [-- dB] Arg database to use
- -C [-- collection] Arg collection to use (some commands)
- -U [-- username] Arg Username
- -P [-- Password] Arg Password
- -- Dbpath Arg directly access your D data files in this path,
- Instead of connecting to a mongod instance
- -V [-- verbose] Be more verbose (include multiple times for more
- Verbosity e.g.-vvvvv)
- Falcon@www.fwphp.cn ~ /MongoDB/bin] $./mongorestore-d test-C user test/user. bson
- Connected to: 127.0.0.1
- Test/test/user. bson
- Going into namespace [test. User]
- 100000 objects
10 million records in the User table have been restored.
- > Show collections
- System. Indexes
- User
- > DB. User. Find ();
- {"_ Id": objectid ("4b9c8db08ead0e3104000000"), "uid": 1, "username": "falcon. C-1 "}
- {"_ Id": objectid ("4b9c8db08ead0e310410000"), "uid": 2, "username": "falcon. C-2 "}
- {"_ Id": objectid ("4b9c8db08ead0e310420000"), "uid": 3, "username": "falcon. C-3 "}
- {"_ Id": objectid ("4b9c8db08ead0e310430000"), "uid": 4, "username": "falcon. C-4 "}
- {"_ Id": objectid ("4b9c8db08ead0e310440000"), "uid": 5, "username": "falcon. C-5 "}
- .................
- Has more
MongoDB also provides an HTTP interface for viewing the running status and restfull
The default port number is 28017.