The first part of the basic chapter fourth MongoDB Quick Start

Source: Internet
Author: User
Tags mongodb collection mongodb support



Statement: The article is mainly from the "MongoDB actual Combat" a book, the main want to learn MongoDB knowledge through the book, deepen understanding, so write in their own blog, as a record, in the final chapter, there will be a collection of MongoDB database application Java EE Web application.



The MongoDB Shell is an interactive JavaScript shell that comes with MongoDB and is used to manipulate and manage MongoDB.



Use the./mongo--help to view the relevant connection parameters, which will illustrate the use of mongodb shell from common operations such as inserting, querying, modifying, deleting, and so on.



1.1. Start the database



MongoDB installation, configuration, you must start it before you can use it, how to start it? 3 ways to launch an instance are shown below.



1.1.1, command-line mode start



MongoDB default Storage Data directory is/data/db/(or C:\data\db), the default port is 27017, the default HTTP port is 28017, of course you can also modify into different directories, only need to specify the DBPath parameters:





./mongod--dbpath=/var/mongodb/data/--logpath/var/mongodb/logs/log.log-fork


Description:--fork indicates that the background process started.


1.1.2, configuration file mode startup



If it is a professional DBA, then the instance will be started with a lot of parameters to make the system run very stable, so that you can start with a long string of parameters after Mongod, it seems very confusing and poor management and maintenance, then what is the way to make these parameters organized? MongoDB also supports the same way that MySQL reads the boot configuration file to start the database, and the contents of the configuration file are as follows:



[Email protected] bin]# VI/ETC/MONGODB.CNF



dbpath=/var/mongodb/data/



Start with the-f parameter and point to the configuration file to



[Email protected] bin]#/mongod-f/etc/mongodb.cnf



1.1.3, daemon mode start



You can notice that both of the above methods start the MONGDB process in the foreground, but when the session window that starts the MongoDB process is accidentally closed, the MongoDB process will also stop, which is undoubtedly very insecure, Fortunately, MongoDB provides a background daemon way to start the choice, only need to add a--fork parameter, which makes it easier for us to operate the database startup, but if the use of the--fork parameter must also start the--logpath parameter, which is mandatory.



./mongod--dbpath=/var/mongodb/data/--logpath/var/mongodb/logs/log.log-fork



Without the--logpath parameter, you will be prompted:--fork have to is used with--logpath



1.1.4, MongoDB parameter description



The simplest, by executing mongod can start the MongoDB database service, Mongod support a lot of parameters, but there are default values, the most important of which is the need to develop a data file path, or to ensure that the default/data/db/exists and has access rights, otherwise the service will be shut down automatically after startup , that is to say, just make sure that DBPath can start the MongoDB service.



The main parameters of Mongod are:


  • DBPath: Data file storage path, each database will be started to create a subdirectory, to prevent the same instance running multiple times Mongod.lock also saved in this directory.
  • LogPath: Error log file.
  • Logappend: Error log in Append mode (default is overwrite mode)
  • BIND_IP: External service binding IP, generally set to null, and binding on all available IP on this machine, if necessary, can be independently developed.
  • PORT: External service port, Web management port on this port based on +1000.
  • Fork: Run the service after the daemon form.
  • Journal: Turn on the log function, reduce the recovery time of single machine failure by saving the Operation Log class, formally join after 1.8 version, replace the Dur parameter in version 1.7.5.
  • Syncdelay: The time of the system to flush the disk synchronously, in seconds, the default is 60 seconds.
  • DIRECTORYPERDB: Each db is stored in a separate directory, it is recommended to set this parameter, the domain MySQL is a separate table space similar.
  • Maxconns: Maximum number of connections.
  • Repairpath: Repair When executing the temporary directory, if the joural is not turned on, the exception is restarted after the machine, you must perform the repair operation.
in the source code, Mongod parameters are divided into general parameters, Windows parameters, replication parameters, replica set parameters, as well as the implied parameters, which are listed above are general parameters, if you want to configure replication, replica Set, and so on, also need to set the corresponding parameters, here do not expand, followed by a special section to tell, the implementation of Mongod--help can see the interpretation of most parameters, but also some implicit parameters, can only be obtained by looking (see Db.cpppo::options_ Description Hidden_options ("Hidden options");), the implied parameters are either still in development or ready to be discarded, so it is not recommended in a production environment. you may have noticed that there are no parameters related to memory size in the Mongod parameter, yes, MongoDB uses the OS mmap mechanism to cache data file data, it does not currently provide a caching mechanism, so the benefit is the code is simple, mmap in the amount of data is not more efficient than memory, However, when the data exceeds the available memory of the system, the write performance may be less stable and prone to ups and downs, but in the latest version 1.8, the situation has improved somewhat relative to the previous version. With so many parameters, a full write on the command line can be messy and poorly managed, so Mongod supports writing parameters to a configuration text file, and then referencing the configuration file through the Config parameter:./mongod--config/etc/mongo.cnf
1.2. Stop the databaseMongoDB provides a very rich stop database command if control-c, send Shutdownserver () specify, and send UNIX system interrupt signals. 1.2.1, control-cIf the connection status is handled, the MongoDB instance can be stopped directly by Control-c, as follows:[email protected] bin]#./mongo
MongoDB Shell version:2.6.6
Connecting To:test
Welcome to the MongoDB shell.
For interactive help, type ' help '.
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the Support group
Http://groups.google.com/group/mongodb-user
> ^c
Bye
[Email protected] bin]#
1.2.2, Shutdownserver () directiveIf the connection status is processed, the db.shutdownserver () command can be sent directly through the Admin library to stop the MongoDB instance, as follows:
[Email protected] bin]#./mongo
MongoDB Shell version:2.6.6
Connecting To:test
> Use admin
Switched to DB admin
> db.shutdownserver ()
2015-01-04t10:23:44.506+0800 Dbclientcursor::init Call () failed
Server should is down ...
2015-01-04t10:23:44.519+0800 trying reconnect to 127.0.0.1:27017 (127.0.0.1) failed
2015-01-04t10:23:44.521+0800 warning:failed to connect to 127.0.0.1:27017, reason:errno:111 Connection refused
2015-01-04t10:23:44.521+0800 Reconnect 127.0.0.1:27017 (127.0.0.1) failed failed couldn ' t connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed
>
1.2.3, Unix system directivesAfter you find the process for the instance, you may be able to stop the process by sending a kill-2 pid or kill-15 pid, as follows:
[Email protected] bin]# PS aux|grep mongod
Root 2676 1.4 3.0 467208 30668? Sl 10:24 0:00./mongod--dbpath=/var/mongodb/data/--logpath/var/mongodb/logs/log.log-fork
Root 2695 0.0 0.0 103236 864 pts/1 s+ 10:24 0:00 grep mongod
Note: Do not use the kill-9 pid to kill the MongoDB process, which can cause data corruption in MongoDB. [email protected] bin]#kill-2 2676

1.3. Connect to the databaseNow we can use our own MongoDB shell tool to operate the database, we can also use a variety of programming language driver to use MONGDB, but the own MongoDB shell tool can be convenient for us to manage the database, new open a session input:/ Usr/local/mongodb/bin/mongo, if the following prompt appears, then you will be connected to the database, you can operate. [email protected] bin]#./mongo
MongoDB Shell version:2.6.6
Connecting To:test
Welcome to the MongoDB shell.
For interactive help, type ' help '.
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the Support group
Http://groups.google.com/group/mongodb-user
>
The default shell is connected to the native localhost of the test library, "connection to:" This will show you are using the name of the database, if you want to change the database can be used mydb to achieve.
1.4. Inserting RecordsLet's create a set of test and write some data, build two objects J and T, and save it to the central section, in the example ">" to indicate a prompt with the shell. > A={name: "Mongo"}
{"Name": "MONGO"}
> B={x:4}
{"X": 4}
> Db.xuz.save (a)
Writeresult ({"ninserted": 1})
> db.xuz.save (b)
Writeresult ({"ninserted": 1})
> Db.xuz.find ();
{"_id": ObjectId ("54a8a4ff2db3e1b27d0e5203"), "name": "MONGO"}
{"_id": ObjectId ("54a8a5042db3e1b27d0e5204"), "X": 4}
Description:
    • There is no need to pre-create a collection that is created automatically the first time you insert data.
    • In the document can actually store any structure of data, of course, in the actual application of our stored or the same type of document collection, this feature can actually be very flexible in the application, you do not need to like ALTER TABLE statement to modify your data structure.
    • Each time the data is inserted, there will be an ID in the collection, called _id.
add some more data below:> for (var i=1;i<=50;i++) Db.xuz.save ({x:5,j:i});
Writeresult ({"ninserted": 1})
> Db.xuz.find ();
{"_id": ObjectId ("54a8a4ff2db3e1b27d0e5203"), "name": "MONGO"}
{"_id": ObjectId ("54a8a5042db3e1b27d0e5204"), "X": 4}
{"_id": ObjectId ("54a8a5a427681683ca2c2466"), "X": 5, "J": 1}
{"_id": ObjectId ("54a8a5a427681683ca2c2467"), "X": 5, "J": 2}
{"_id": ObjectId ("54a8a5a427681683ca2c2468"), "X": 5, "J": 3}
{"_id": ObjectId ("54a8a5a427681683ca2c2469"), "X": 5, "J": 4}
{"_id": ObjectId ("54a8a5a427681683ca2c246a"), "X": 5, "J": 5}
{"_id": ObjectId ("54a8a5a427681683ca2c246b"), "X": 5, "J": 6}
{"_id": ObjectId ("54a8a5a427681683ca2c246c"), "X": 5, "J": 7}
{"_id": ObjectId ("54a8a5a427681683ca2c246d"), "X": 5, "J": 8}
{"_id": ObjectId ("54a8a5a427681683ca2c246e"), "X": 5, "J": 9}
{"_id": ObjectId ("54a8a5a427681683ca2c246f"), "X": 5, "J": 10}
{"_id": ObjectId ("54a8a620e708df7187eb2dd8"), "X": 5, "J": 1}
{"_id": ObjectId ("54a8a620e708df7187eb2dd9"), "X": 5, "J": 2}
{"_id": ObjectId ("54a8a620e708df7187eb2dda"), "X": 5, "J": 3}
{"_id": ObjectId ("54a8a620e708df7187eb2ddb"), "X": 5, "J": 4}
{"_id": ObjectId ("54A8A620E708DF7187EB2DDC"), "X": 5, "J": 5}
{"_id": ObjectId ("54a8a620e708df7187eb2ddd"), "X": 5, "J": 6}
{"_id": ObjectId ("54a8a620e708df7187eb2dde"), "X": 5, "J": 7}
{"_id": ObjectId ("54a8a620e708df7187eb2ddf"), "X": 5, "J": 8}
Type "It" for more
NOTE: Notice here that the number of loops is 50, but only to 20th, and other data is not shown, if you want to continue to query the following data only need to use the IT command, will continue to display the following data:> It
{"_id": ObjectId ("54a8a620e708df7187eb2de0"), "X": 5, "J": 9}
{"_id": ObjectId ("54a8a620e708df7187eb2de1"), "X": 5, "J": 10}
{"_id": ObjectId ("54a8a620e708df7187eb2de2"), "X": 5, "J": 11}
{"_id": ObjectId ("54a8a620e708df7187eb2de3"), "X": 5, "J": 12}
{"_id": ObjectId ("54a8a620e708df7187eb2de4"), "X": 5, "J": 13}
{"_id": ObjectId ("54a8a620e708df7187eb2de5"), "X": 5, "J": 14}
{"_id": ObjectId ("54a8a620e708df7187eb2de6"), "X": 5, "J": 15}
{"_id": ObjectId ("54a8a620e708df7187eb2de7"), "X": 5, "J": 16}
{"_id": ObjectId ("54a8a620e708df7187eb2de8"), "X": 5, "J": 17}
{"_id": ObjectId ("54a8a620e708df7187eb2de9"), "X": 5, "J": 18}
{"_id": ObjectId ("54a8a620e708df7187eb2dea"), "X": 5, "J": 19}
{"_id": ObjectId ("54a8a620e708df7187eb2deb"), "X": 5, "J": 20}
{"_id": ObjectId ("54a8a621e708df7187eb2dec"), "X": 5, "J": 21}
{"_id": ObjectId ("54a8a621e708df7187eb2ded"), "X": 5, "J": 22}
{"_id": ObjectId ("54a8a621e708df7187eb2dee"), "X": 5, "J": 23}
{"_id": ObjectId ("54a8a621e708df7187eb2def"), "X": 5, "J": 24}
{"_id": ObjectId ("54a8a621e708df7187eb2df0"), "X": 5, "J": 25}
{"_id": ObjectId ("54a8a621e708df7187eb2df1"), "X": 5, "J": 26}
{"_id": ObjectId ("54a8a621e708df7187eb2df2"), "X": 5, "J": 27}
{"_id": ObjectId ("54a8a621e708df7187eb2df3"), "X": 5, "J": 28}
Type "It" for more
technically find () returns a cursor object, but in the example above, there is no variable for a cursor, so the shell automatically iterates through the cursor, returns an initialized set, and allows us to continue with the IT iteration output, of course, we can also directly use the cursor output, But this is what the cursor section is about.
1.5. _id Keyin the data types that MongoDB supports, _id is the product of its own, and the following is a brief introduction to it. each document stored in the MongoDB collection has a default primary key _id, which is fixed, it can make MongoDB support any data type, default is Objectid, in the relational database schema design, Primary keys are mostly numeric, such as commonly used int and long, and more unobstructed is the value of the primary key is derived from the database, the order of the primary key value is sometimes marked with a certain logic, the reverse view of MongoDB, it was originally designed to be located in a distributed storage system, so it does not support the original self-increment primary key. _id Key examples illustrate:When we write a document to a collection, the system automatically generates a key named _id, such as:
> Db.xuz.find ();
{"_id": ObjectId ("54a8a4ff2db3e1b27d0e5203"), "name": "MONGO"}
{"_id": ObjectId ("54a8a5042db3e1b27d0e5204"), "X": 4}
There is an extra type of Objectid key, which is not specified at the time of insertion, which is somewhat similar to Oracle's ROWID information, which is automatically generated. in MongoDB, each collection must have a field called _id, the field type default is Objectid, in other words, the field type can be not objectid, for example: {"_id": ObjectId ("54a8a621e708df7187eb2e08"), "X": 5, "J": 49}
{"_id": ObjectId ("54a8a621e708df7187eb2e09"), "X": 5, "J": 50}
{"_id": 3, "name": "Zhangsan"}
Although the type of _id can be freely specified, it must be unique in the same set, and if a duplicate value is inserted, the system throws an exception, as follows: > Db.xuz.insert ({_id:3, "name": Zhaoliu});
2015-01-04t10:41:26.289+0800 Referenceerror:zhaoliu is not defined
> Db.xuz.insert ({_id:3, "name": "Zhaoliu"});
Writeresult ({
"ninserted": 0,
"Writeerror": {
"Code": 11000,
"ErrMsg": "Insertdocument:: Caused by:: 11000 E11000 duplicate key error index:test.xuz.$_id_ dup key: {: 3.0}"
}
})
Note: Inserting the same document is not allowed because a _id=3 record has been inserted in the previous section.





The first part of the basic chapter fourth MongoDB Quick Start


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.