MongoDB Beginner Learning (a): MongoDB Installation and management

Source: Internet
Author: User
Tags auth deprecated mongodump mongorestore

Once with MySQL database, all day is to write a large heap of SQL statements. To remember that these sqlkeyword are going to take a few days, write the eggs have exploded, when the contact with MongoDB, found not to write SQL, instantly think tall, instantly produced the impulse to learn to use it.

1.MongoDB Brief Introduction

MongoDB is a powerful, flexible. An extensible way to store data.

It extends the many useful functions of a relational database, such as a secondary index. range queries and sorting. MongoDB has a very rich feature, such as the built-in support for MapReduce-type aggregation. and support for geo-spatial indexes.

There are very many very many features ...

For entry-level people. These are all floating clouds, and I can't feel the capacity now. Also can not realize its horizontal expansion, not to realize its rate, these are when we play to a certain situation will be concerned about the problem.

I simply think its advantage is easy to get started. Provides a series of APIs that do not have to write SQL statements.

As to how it differs from relational databases. What are the advantages or shortcomings that need to be improved is a matter of the future.

Installation of 2.MongoDB

MongoDB's official website is downloaded, according to the system Windows or Linux or other download 32-bit or 64-bit, and then unzip the installation.

I installed it on Linux. It started with Yum installed on its own virtual machine, and later was installed on its own user via SECURECRT to connect to the other server, so that it could play its own mongodb and not hang up the server. But this can not be through Yum, the source code installation seems to have a lot of software dependencies, so on the official web download a Linux version, and then upload via SFTP to the server after decompression directly to use.

Management of 3.MongoDB

After the decompression into the Bin folder, inside are some of the files can be run, Mongo,mongod. Mongodump,mongoexport and so on. Let's talk about their role later.

1). Start and stop MongoDB

By running Mongod to start mongodbserver,mongod There are a lot of configuration startup options that can be viewed through Mongod--help, with some basic options:

--dbpath: Specifies the data folder, which is/data/db/by default. Each mongod process requires a separate folder, and a Mongod.lock file is created in the Data folder when Mongod is started, preventing other mongod processes from using the Data folder.

--port: Specifies the port that the server listens on, which is 27017 by default.

--fork: Executes MongoDB as a daemon.

--logpath: Specifies the log output path, which is assumed to be output at the terminal if not specified. Each boot overwrites the original log, assuming that you do not want to overwrite with the--logappend option.

--config: Specifies a configuration file that loads various options not specified on the command line. We can say the options we need to write in a file, and then use this option to specify that the file does not have to be written every time you start Mongod.

For example, my profile mongodb.conf has the following configuration:

Port = 9352#fork = True              #为凝视 #logpath = Mongodb.logdbpath = data/db

Run Mongod start Mongodbserver Specify the configuration file:

[[email protected] bin]$./mongod--config mongodb.conf 2014-06-05t17:11:13.118+0800 [Initandlisten] MongoDB starting:pid=18077 port=9352 dbpath=data/db 64-bit host=server0.1692014-06-05t17:11:13.119+0800 [Initandlisten] db Version v2.6.12014-06-05t17:11:13.119+0800 [Initandlisten] git version: 4b95b086d2374bdcfcdf2249272fb552c9c726e82014-06-05t17:11:13.119+0800 [Initandlisten] Build Info:linux build14.nj1.10gen.cc 2.6.32-431.3.1.el6.x86_64 #1 SMP Fri Jan 3 21:39:27 UTC x86_64 boost_lib_version=1_492014-06-05 t17:11:13.119+0800 [Initandlisten] allocator:tcmalloc2014-06-05t17:11:13.119+0800 [Initandlisten] options: {config: "Mongodb.conf", Net: {port:9352}, storage: {dbPath: "data/db"}}2014-06-05t17:11:13.246+0800 [Initandlisten] Journal dir=data/db/journal2014-06-05t17:11:13.246+0800 [Initandlisten] recover:no journal files present, no recovery needed2014-06-05t17:11:15.333+0800 [Initandlisten] Preallocateisfaster=true 20.742014-06-05t17:11:17.692+0800 [ InitandlisTen] Preallocateisfaster=true 13.722014-06-05t17:11:20.858+0800 [Initandlisten] Preallocateisfaster=true 23.862014-06-05t17:11:20.858+0800 [Initandlisten] preallocateisfaster check took 7.612 secs2014-06-05t17:11:20.858+ 0800 [Initandlisten] preallocating a journal file data/db/journal/prealloc.02014-06-05t17:11:23.121+0800 [ Initandlisten] File preallocator progress:492830720/1073741824 45%2014-06-05t17:11:26.424+0800 [Initand             Listen] File preallocator progress:681574400/1073741824 63%2014-06-05t17:11:29.004+0800 [Initandlisten] File preallocator progress:964689920/1073741824 89%2014-06-05t17:11:34.558+0800 [Initandlisten] Preall  Ocating a journal file data/db/journal/prealloc.12014-06-05t17:11:37.089+0800 [initandlisten] File Preallocator progress:524288000/1073741824 48%2014-06-05t17:11:40.090+0800 [Initandlisten] File preallocator Progre ss:807403520/1073741824 75%2014-06-05t17:11:43.063+0800[Initandlisten] File preallocator progress:1017118720/1073741824 94%2014-06-05t17:11:48.020+0800 [Initandlisten] preallocating a Jo urnal file data/db/journal/prealloc.22014-06-05t17:11:51.040+0800 [initandlisten] File Preallocator progress:5 76716800/1073741824 53%2014-06-05t17:11:54.039+0800 [Initandlisten] File preallocator progress:80740352 0/1073741824 75%2014-06-05t17:11:57.026+0800 [Initandlisten] File preallocator progress:1069547520/1073 741824 99%2014-06-05t17:12:01.985+0800 [Fileallocator] Allocating new datafile data/db/local.ns, filling with zeroes ... 2014-06-05t17:12:01.985+0800 [fileallocator] Creating directory data/db/_tmp2014-06-05t17:12:02.285+0800 [ Fileallocator] Done allocating datafile Data/db/local.ns, SIZE:16MB, took 0.167 secs2014-06-05t17:12:02.315+0800 [FileA Llocator] Allocating new datafile data/db/local.0, filling with zeroes ... 2014-06-05t17:12:02.413+0800 [Fileallocator] Done allocating DataFile data/db/local.0, SIZE:64MB, took 0.097 secs2014-06-05t17:12:02.434+0800 [Initandlisten] Build index on:local. Startup_log properties: {v:1, key: {_id:1}, Name: "_id_", ns: "Local.startup_log"}2014-06-05t17:12:02.434+0800 [init Andlisten] Added index to empty collection2014-06-05t17:12:02.456+0800 [initandlisten] command local $cmd command:cre Ate {create: "Startup_log", size:10485760, capped:true} ntoreturn:1 keyupdates:0 numyields:0 reslen:37 494ms2014-06-0 5t17:12:02.457+0800 [Initandlisten] waiting for connections on port 9352

Start Mongodbserver successfully, listen to port9352, wait for the client to connect. Assuming that the log files are specified, the logs are output to the specified log file. Assuming the daemon is set, a child process is created. The stepfather process exits when Mongodbserver is started.

It is important that MongoDB is safely stopped. Since there may be data in the cache that is not written to the disk, a secure stop is to first write the data into the disk and then end the MongoDB process. can use CTRL + C directly to stop Mongodbserver. can also be through the client. MONGO is a JavaScript shell that initiates its own active connection to Mongodbserver, so MONGO is also a mongodbclient. It can execute no matter what JavaScript program. can also operate the database.

Take a look down MONGO stop mongodbserver:

[Email protected] bin]$/mongo--port 9352MongoDB Shell version:2.6.1connecting to:127.0.0.1:9352/test> show Dbsadm In  (empty) local  0.078GBtest   (empty) > Use adminswitched to DB admin> db.shutdownserver () 2014-06-05t17:21:59.263+0800 Dbclientcursor::init Call () Failedserver should is down ... 2014-06-05t17:21:59.265+0800 trying reconnect to 127.0.0.1:9352 (127.0.0.1) failed2014-06-05t17:21:59.266+0800 warning:failed to connect to 127.0.0.1:9352, reason:errno:111 Connection refused2014-06-05t17:21:59.266+0800 Reconnect 127.0.0.1:9352 (127.0.0.1) failed failed couldn ' t connect to server 127.0.0.1:9352 (127.0.0.1), connection attempt failed& Gt Exitbye

As can be seen from the above, we connect to the local 9352porttest database. Admin is a root database, this database is used to manage the whole mongodb, not no matter who can stop mongodbserver, so use the admin to run Shutdownserver () to stop.

2). Safety and Certification

The above is connected to Mongodbserver by MONGO the client. No matter what the security certification, that is, no matter who can connect, of course, can be in a trusted environment to run it, to ensure that only a credible machine skills to access it, but also to the authentication of a single connection. Each MongoDB database can have many users, assuming security checks are turned on. Only the database authentication user ability to run related operations. Users of the admin can read and write to any database, and users of other databases can only run operations related to permissions.

Before you start the security check, create several users:

> Use adminswitched to DB admin> db.adduser ("TP", "12345") warning:the ' addUser ' shell Helper is DEPRECATED.  Please use the ' createUser ' insteadsuccessfully added User: {"user": "TP", "Roles": ["root"]}> use testswitched to DB Test> db.adduser ("Test1", "12345", True) warning:the ' addUser ' shell Helper is DEPRECATED.  Please use ' createUser ' insteadsuccessfully added User: {"user": "Test1", "Roles": ["read"]}> db.adduser ("Test2", "12345") warning:the ' addUser ' shell Helper is DEPRECATED. Please use the ' createUser ' insteadsuccessfully added User: {"user": "Test2", "Roles": ["Dbowner"]}> use Adminswitche D to DB admin> show collectionssystem.indexessystem.userssystem.version> db.system.users.find () {"_id": "  ADMIN.TP "," User ":" TP "," DB ":" admin "," credentials ": {" MONGODB-CR ":" E4aafd1c8d19d9e490192fe5bf43ffe0 "}," Roles ": [{"Role": "Root", "db": "Admin"}]} {"_id": "Test.test1", "User": "Test1", "DB": "Test", "credentials": {"MONGODB-CR": "2da1438b5a04dd46cfdf97c40a3c6d71"}, "Roles": [{"Role": "read", "DB": "Test"}]} {"_id": "Test.test2", "User": "Test2", "DB": "Test", "credentials": {"MONGODB-CR": "4accbd2cb1dce25ed8b3b162103b0b87"}, "Roles": [{"Role": "DB Owner "," DB ":" Test "}]}

Added a user tp to admin. Two users Test1 and Test2,adduser () were added to the test database with three parameters. The first one is username, the second is password, the third is just the read state, set to True to read only. As can be seen from the user collection system.users, TP is the superuser in the admin database. There is root authority, test1 only have Read permission, Test2 is Dbowner, can read also can write. AddUser can also change user password and read-only status. The following restarts the Mongodbserver and joins the--auth command option to turn on the security check. Then connect via MONGO:

> Show dbs2014-06-05t17:59:57.519+0800 listdatabases failed:{"OK": 0, "errmsg": "Not authorized on ADM In to execute command {listdatabases:1.0} ', ' Code ': ' at src/mongo/shell/mongo.js:47> ' use testswitched to DB test> Db.auth ("Test1", "12345") 1> show collectionspeoplesystem.indexes> Db.people.find () {"_id": ObjectId ( "53903f7af73bb0df22f8e4a6"), "name": "Mary", "Age": Ten}> Db.people.insert ({"Name": "Join", "age":) Writeresult (  {"Writeerror": {"code": "ErrMsg": "Not authorized on test to execute command {insert: \ "People\", documents: [{_id:objectid (' 53903fd6959e902814f56d8c '), name: \ "Join\", age:20.0}], ordered:t Rue} "}" > Db.auth ("test2", "12345") 1> Db.people.find () {"_id": ObjectId ("53903f7af73bb0df22f8e4a6"), "name ":" Mary "," Age ":}> Db.people.insert ({" Name ":" Join "," Age ": $}) Writeresult ({" ninserted ": 1}) > Use admin Switched to DB admin> db. Auth ("TP", "12345") 1> show Dbsadmin 0.078GBlocal 0.078GBtest 0.078GB 

User authentication is not performed after connecting to Mongodbserver. So nothing to do, when using the test database and user authentication, you can view the collection in the test library, because Test1 can only read and not write, so find can succeed and insert failure, test2 can read and write, User authentication with the Admin database allows you to view a full list of databases. In fact, this kind of certification is not very large, just a way, the safest way is to restrict access.

3). Data Backup

①. Data file backup

The simplest backup is the backup of the data file, which is the direct assignment data/db this folder. Since we have already specified the Data folder is data/db, then mongodb more data are here, but one problem is that the latest data is still in the cache, not synchronized to disk. Ability to stop Shutdownserver () before backup.

However, this will affect MongoDB's normal work.

②.mongodump and Mongorestore

There are also mongodump and mongorestore two executables in the bin, a backup of a database from MongoDB that can be backed up when MongoDB is executing. For example, back up the test database. The backed up database file is then poured into another mongodbserver.

Such backups are not up-to-date data, only data that has been written to MongoDB, and possibly other data is not written in the cache, then this part of the data is not backed up. Mongodump and Mongorestore are also able to query all options through--HELP.

[Email protected] bin]$/mongodump--port 9352-d test-o test_dataconnected to:127.0.0.12014-06-05t19:00:03.381+0800 D Atabase:test      to     test_data/test2014-06-05t19:00:03.411+0800    test.system.indexes to test_data/test/ system.indexes.bson2014-06-05t19:00:03.426+0800             1 documents2014-06-05t19:00:03.426+0800    test.test to test _data/test/test.bson2014-06-05t19:00:03.463+0800             1 documents2014-06-05t19:00:03.464+0800    Metadata for Test.test to Test_data/test/test.metadata.json

-D is the specified database, and-O is the output backup file, which backs up the test database to a test_data file.

[Email protected] bin]$/mongorestore--port 9352-d temple--drop test_data/test/connected to:127.0.0.1:93522014-06-0 5t19:05:53.454+0800 test_data/test/people.bson2014-06-05t19:05:53.454+0800    going into namespace [temple.people ]2014-06-05t19:05:53.454+0800     dropping2 Objects found2014-06-05t19:05:53.454+0800    Creating index: {key: {_ Id:1}, Name: "_id_", ns: "Temple.people"}[[email protected] bin]$./mongo--port 9352MongoDB Shell Version:2.6.1connec Ting to:127.0.0.1:9352/test> show dbsadmin   0.078GBlocal   0.078GBtemple  0.078GBtest    0.078GB

The test database backed up above is now imported into the temple database again. The--drop representative assumes that the temple database will delete all of the collections. Not specified will be merged with the collection in the original temple.

③.mongoexport and Mongoimport

As mentioned above, Mongodump and Mongorestore are backing up a database. So Mongoexport and Mongoimport are backing up a table in a database, the same way you can see all of the options through--help, and of course mongoexport is a backup that doesn't count, but it doesn't have to be the latest data.

[Email protected] bin]$/mongoexport--port 9352-d test-c people-o Prson connected to:127.0.0.1:9352exported 2 Recor Ds[[email protected] bin]$ cat Prson {"_id": {"$oid": "53903f7af73bb0df22f8e4a6"}, "name": "Mary", "Age": Ten} {"_i D ": {" $oid ":" 53903ff6959e902814f56d8d "}," name ":" Join "," age ":}[[email protected] bin]$./mongoimport--port 9 352-d temple-c user Prson connected to:127.0.0.1:93522014-06-05t19:14:00.555+0800 imported 2 Objects[[email protected] bin]$./mongo--port 9352MongoDB Shell version:2.6.1connecting to:127.0.0.1:9352/test> use templeswitched to DB Templ E> show Collectionssystem.indexesuser> Db.user.find () {"_id": ObjectId ("53903f7af73bb0df22f8e4a6"), "name": " Mary "," age ": {" _id ": ObjectId (" 53903ff6959e902814f56d8d ")," name ":" Join "," Age ": 20}

-C represents the collection collection, which backs up the people collection from the test library to a Prson file and then into the user collection in the Temple library.

④.fsync and Locks

Mongodump and Mongoexport are able to keep mongodbserver for backup, but lose the ability to get real-time data. The Fsync command can also back up real-time data in the case of MongoDB, and its implementation is actually locked. Prevents write operations to the database, and then writes the data for the buffer to disk. Back up before unlocking. During this time, no matter what the write operation to the database will be blocked. Until the lock is released.

> Db.runcommand ({"Fsync": 1, "Lock": 1}) {        "info": "Now locked against writes, use Db.fsyncunlock () to unlock", 
    "seealso": "Http://dochub.mongodb.org/core/fsynccommand", "        OK": 1}>> between this backup, run no matter what insert operation will clog > > Db.fsyncunlock () {"OK": 1, "info": "Unlock Completed"}

I think in fact real-time is also relative. Lock the database for write. Then the latest data is still not backed up.

MongoDB Beginner Learning (a): MongoDB Installation and management

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.