MongoDB database documentation

Source: Internet
Author: User
Tags failover findone mongodump mongorestore

 

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

  1. Falcon@www.fwphp.cn ~ /MongoDB] $ bin/Mongo
  2. MongoDB shell version: 1.2.4-
  3. URL: Test
  4. Connecting to: Test
  5. Type "help" for help
  6. > Help
  7. Help
  8. Show DBS show Database Name
  9. Show collections shows the collection of the current database
  10. Show users
  11. Show profile: displays the system overview with the last system time greater than 1 ms
  12. Use <dB Name> switch to database
  13. DB. Help () Help on DB Methods
  14. DB. Foo. Help () Help on collection methods
  15. DB. Foo. Find () List objects in collection foo
  16. DB. Foo. Find ({A: 1}) List objects in Foo where a = 1
  17. It result of the last line evaluated; use to further iterate
  18. > Show DBS has two databases by default.
  19. Admin
  20. Local
  21. > Switch use admin to the admin database.
  22. Switched to DB Admin
  23. > Show collections: displays the collection below the admin Database
  24. 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:

  1. > DB. createcollection ("user ");
  2. {"OK": 1}
  3. > Show collections
  4. System. Indexes
  5. User
  6. >


Insert data:

  1. > DB. User. insert ({uid: 1, Username: "falcon. c", age: 25 });
  2. > DB. User. insert ({uid: 2, Username: "AABC", age: 24 });


Query data:

  1. > DB. User. Find ();
  2. {"_ Id": objectid ("4b81e74c1f0fd3b9545cba43"), "uid": 1, "username": "falcon. c", "Age": 25}
  3. {"_ 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.

  1. > DB. User. Find ({uid: 1 });
  2. {"_ 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:

  1. > DB. User. Update ({uid: 1}, {$ set: {age: 26 }})
  2. > DB. User. Find ();
  3. {"_ Id": objectid ("4b81e76f1f0fd3b9545cba45"), "uid": 1, "username": "falcon. c", "Age": 26}
  4. {"_ Id": objectid ("4b81e7701f0fd3b9545cba46"), "uid": 2, "username": "AABC", "Age": 24}
  5. > DB. User. Update ({uid: 1}, {$ Inc: {age:-1 }})
  6. > DB. User. Find ();
  7. {"_ Id": objectid ("4b81e76f1f0fd3b9545cba45"), "uid": 1, "username": "falcon. c", "Age": 25}
  8. {"_ Id": objectid ("4b81e7701f0fd3b9545cba46"), "uid": 2, "username": "AABC", "Age": 24}
  9. >


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

  1. > DB
  2. Admin


Want to switch to the Test Database

  1. > Use test
  2. Switched to DB Test
  3. > DB
  4. Test


You can enter

  1. > Show collections
  2. System. Indexes
  3. User


If you want to know which commands MongoDB supports, you can directly enter help

  1. > Help
  2. Help
  3. Show DBS show database names
  4. Show collections show collections in current database
  5. Show users show users in current database
  6. Show profile show most recent system. Profile entries with time> = 1 ms
  7. Use <dB Name> set curent database to <dB Name>
  8. DB. Help () Help on DB Methods
  9. DB. Foo. Help () Help on collection methods
  10. DB. Foo. Find () List objects in collection foo
  11. DB. Foo. Find ({A: 1}) List objects in Foo where a = 1
  12. It result of the last line evaluated; use to further iterate


If you want to know the methods supported by the current database:

  1. > DB. Help ();
  2. DB methods:
  3. DB. adduser (username, password) add authorized database users
  4. DB. Auth (username, password) access authentication
  5. DB. clonedatabase (fromhost) clone Database
  6. DB. commandhelp (name) returns the help for the command
  7. DB. copydatabase (fromdb, todb, fromhost)
  8. DB. createcollection (name, {size:..., capped:..., Max:...}) create a table
  9. DB. currentop () displays the current operation in the DB
  10. DB. dropdatabase () Delete the current database
  11. DB. eval (func, argS) run code server-side
  12. DB. getcollection (cname) Same As DB ['cname'] or db. cname
  13. DB. getcollectionnames () Get the table name of the current database
  14. DB. getlasterror ()-Just returns the err MSG string
  15. DB. getlasterrobj ()-return full status object
  16. DB. getmongo () Get the server connection object
  17. DB. getmongo (). setslaveok () allow this connection to read from the nonmaster member of a replica pair
  18. DB. getname ()
  19. DB. getpreverror ()
  20. DB. getprofilinglevel ()
  21. DB. getreplicationinfo ()
  22. DB. getsisterdb (name) Get the dB at the same server as this onew
  23. DB. Killop () kills the current operation in the DB
  24. DB. printcollectionstats () prints the status information of each table
  25. DB. printreplicationinfo () prints the replication status of the primary database.
  26. DB. printslavereplicationinfo () prints the copy status information from the database
  27. DB. printshardingstatus () prints the shard status information
  28. DB. removeuser (username) delete database users
  29. DB. repairdatabase () repair Database
  30. DB. reseterror ()
  31. DB. runcommand (cmdobj) run a database command. If cmdobj is a string, turns it into {cmdobj: 1}
  32. DB. setprofilinglevel (level) 0 = off 1 = slow 2 = all
  33. DB. shutdownserver ()
  34. 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:

  1. > DB. User. Help (); User indicates the table name.
  2. Dbcollection help
  3. Number of rows in the DB. Foo. Count () Statistical table
  4. DB. Foo. datasize () statistics table data size
  5. DB. Foo. Distinct (key)-eg. DB. Foo. Distinct ('x') Division by given conditions
  6. DB. Foo. Drop () Drop the collection to delete a table
  7. DB. Foo. dropindex (name) deletes the specified index
  8. DB. Foo. dropindexes () Delete All indexes
  9. DB. Foo. ensureindex (keypattern, options)-options shocould be an object with these possible fields: name, unique, and dropdups add Indexes
  10. 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
  11. E.g. DB. Foo. Find ({X: 77}, {Name: 1, x: 1 })
  12. DB. Foo. Find (...). Count ()
  13. DB. Foo. Find (...). Limit (n) searches for data based on conditions and returns the specified number of records.
  14. DB. Foo. Find (...). Skip (N)
  15. DB. Foo. Find (...). Sort (...) Search for sorting
  16. DB. Foo. findone ([query]) queries only one data record by condition
  17. DB. Foo. getdb () Get dB object associated with collection returns the database to which the table belongs.
  18. DB. Foo. getindexes () displays all indexes of the table.
  19. DB. Foo. Group ({key:..., initial:..., reduce:... [, Cond:...]}) grouped by conditions
  20. DB. Foo. mapreduce (mapfunction, performancefunction, <optional Params>)
  21. DB. Foo. Remove (query) delete data based on conditions
  22. DB. Foo. renamecollection (newname) renames the collection to rename the table
  23. DB. Foo. Save (OBJ) save data
  24. DB. Foo. Stats () view the table status
  25. DB. Foo. storagesize ()-distributed des free space allocated to this collection query allocated to the tablespace size
  26. DB. Foo. totalindexsize ()-size in bytes of all the indexes query the size of all indexes
  27. DB. Foo. totalsize ()-storage allocated for all data and Indexes
  28. DB. Foo. Update (query, object [, upsert_bool]) updates data based on conditions.
  29. DB. Foo. Validate ()-slow verification table details
  30. DB. Foo. getshardversion ()-only for use with sharding


MongoDB backup tool mongodump

If you want to back up the database test, for example:

  1. [Falcon@www.fwphp. CN ~ /MongoDB/bin] $./mongodump -- Help
  2. Options:
  3. -- Help produce help message
  4. -H [-- Host] Arg Mongo host to connect
  5. -D [-- dB] Arg database to use
  6. -C [-- collection] Arg collection to use (some commands)
  7. -U [-- username] Arg Username
  8. -P [-- Password] Arg Password
  9. -- Dbpath Arg directly access your D data files in this path,
  10. Instead of connecting to a mongod instance
  11. -V [-- verbose] Be more verbose (include multiple times for more
  12. Verbosity e.g.-vvvvv)
  13. -O [-- Out] Arg (= dump) output directory
  14. Falcon@www.fwphp.cn ~ /MongoDB/bin] $ [color = Blue]./mongodump-d test-O test/[/color]
  15. Connected to: 127.0.0.1
  16. Database: Test to test/test
  17. Test. User to test/user. bson
  18. 100000 objects
  19. Test. system. indexes to test/system. Indexes. bson
  20. 1 objects
  21. Falcon@www.fwphp.cn ~ /MongoDB/bin] $ ls
  22. 2 Mongo mongodump program files mongorestore mongosniff
  23. Dump mongod export Export Import mongos Test


MongoDB data recovery tool mongorestore

View tables in the Test Database

  1. > Show collections
  2. System. Indexes
  3. User


Delete user table

  1. > DB. User. Drop ();
  2. True
  3. > Show collections
  4. System. Indexes


Now, the mongorestore table is used to restore the data backed up by mongodump.

  1. Falcon@www.fwphp.cn ~ /MongoDB/bin] $./mongorestore -- Help
  2. Usage:./mongorestore [Options] [directory or filename to restore from]
  3. Options:
  4. -- Help produce help message
  5. -H [-- Host] Arg Mongo host to connect
  6. -D [-- dB] Arg database to use
  7. -C [-- collection] Arg collection to use (some commands)
  8. -U [-- username] Arg Username
  9. -P [-- Password] Arg Password
  10. -- Dbpath Arg directly access your D data files in this path,
  11. Instead of connecting to a mongod instance
  12. -V [-- verbose] Be more verbose (include multiple times for more
  13. Verbosity e.g.-vvvvv)
  14. Falcon@www.fwphp.cn ~ /MongoDB/bin] $./mongorestore-d test-C user test/user. bson
  15. Connected to: 127.0.0.1
  16. Test/test/user. bson
  17. Going into namespace [test. User]
  18. 100000 objects


10 million records in the User table have been restored.

  1. > Show collections
  2. System. Indexes
  3. User
  4. > DB. User. Find ();
  5. {"_ Id": objectid ("4b9c8db08ead0e3104000000"), "uid": 1, "username": "falcon. C-1 "}
  6. {"_ Id": objectid ("4b9c8db08ead0e310410000"), "uid": 2, "username": "falcon. C-2 "}
  7. {"_ Id": objectid ("4b9c8db08ead0e310420000"), "uid": 3, "username": "falcon. C-3 "}
  8. {"_ Id": objectid ("4b9c8db08ead0e310430000"), "uid": 4, "username": "falcon. C-4 "}
  9. {"_ Id": objectid ("4b9c8db08ead0e310440000"), "uid": 5, "username": "falcon. C-5 "}
  10. .................
  11. Has more


MongoDB also provides an HTTP interface for viewing the running status and restfull
The default port number is 28017.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.