Installation and operation of MongoDB under Linux

Source: Internet
Author: User
Tags gz file tojson

Mongo DB is a non-relational database (NOSQL) that is currently very popular in the IT industry, and its flexible data storage methods are favored by current it practitioners. Mongo DB is a good implementation of object-oriented thinking (Oo idea), in Mongo db each record is a document object. The biggest advantage of Mongo DB is that all data persistence requires no developers to write SQL statements manually, and it is easy to invoke methods to implement CRUD operations.


First, download MongoDB


Go to MongoDB official website download page: https://www.mongodb.org/downloads Download the appropriate version, such as the current Linux x64 bit the latest version: Mongodb-linux-x86_64-2.6.4.tgz


But a little pit daddy is, download link is obviously tgz format, the result is downloaded into GZ format:


Mongodb1


Let's download it and see for yourself.


Second, decompression MongoDB

[Email protected] ~]# gzip-d mongodb-linux-x86_64-2.6.4.gz


Get the mongodb-linux-x86_64-2.6.4, incredibly is a file, not a folder, and online said the difference:



Mongodb2


There seems to be a problem with the previous download! In fact, it should be the tgz file, according to empirical analysis, the download is actually tgz file, displayed as GZ file is only a formal illusion! So, gzip only extracts the outer layer of the compressed package, and actually needs to unzip the TAR archive property!


Then, first rename the extracted file plus the tar format:

[Email protected] ~]# MV mongodb-linux-x86_64-2.6.4 Mongodb-linux-x86_64-2.6.4.tar


Then, unzip with tar:


1 [[Email protected] ~]# tar xvf mongodb-linux-x86_64-2.6.4.tar




Move the extracted folder & rename to/usr/local/mongodb

[Email protected] ~]# mv Mongodb-linux-x86_64-2.6.4/usr/local/mongodb [[email protected] ~]# Cd/usr/local/mongodb/bin /[[email protected] ~]# LL




The Mongod under the bin is the service-side process of MongoDB, MONGO is its client, and other commands are used for MongoDB for other purposes such as MongoDB file export.


Third, start MongoDB

Before starting, specify the data directory of MongoDB, and if not, create one:

[Email protected] ~]# CD/USR/LOCAL/MONGODB [[email protected] mongodb]# mkdir data


Then, execute the following command to start MongoDB:

[Email protected] mongodb]#/usr/local/mongodb/bin/mongod--dbpath=/usr/local/mongodb/data/--logpath=/usr/local/ Mongodb/data/mongodb.log--logappend&


Mongodb5



After successful startup, you can see if the boot was successful, the default port number is 27017, and of course you can specify an unused port at startup.


Mongodb6


Finally, the client Mogo file is soft-linked under/bin for easy execution anywhere:

Ln-s/usr/local/mongodb/bin/mongo/bin/mongo




Now use the MONGO client to access the database:

[Email protected] bin]#/mongo MongoDB shell version:2.6.4 connecting to:test >


Installation is successful!


Iv.. Attached: basic operation


 mongodb Database Basic Usage   SHOW DBS: Show Database List  show Collections: Displays a collection in the current database (similar to a table in a relational database)  show users: Show user use and LT;DB name>: Switch the current database, which is the same as the meaning inside the Ms-sql  db.help (): Displays the database Operations command, which has a lot of commands  db.foo.help (): Display set operation command, also have a lot of commands, Foo refers to the current database, a collection called Foo, not the real Command  db.foo.find (): Data lookup for the Foo collection in the current database (all data is listed because there are no conditions)  db.foo.find ({a: 1}): Look for the Foo collection in the current database, provided the data has a property called a, and A has a value of 1 MongoDB does not have a command to create a database, but has a similar command. For example, if you want to create a "myTest" database, run the use myTest command first, then do something (such as: db.createcollection (' user ')) so that you can create a database called "MyTest". Database Common commands   1, help view command prompt  help  db.help ();  db.yourcoll.help ();  db.youcoll.find (). Help ();  rs.help (); 2, switch/CREATE DATABASE  use Yourdb; When a collection (table) is created, the current database 3 is automatically created, querying all databases  show dbs; 4, delete the current use database  db.dropdatabase (); 5, cloning the database from the designated host  db.clonedatabase ("127.0.0.1"); Cloning data from the database on the specified machine to the current database 6, copying the specified database data from the specified machine to a database  db.copydatabase ("MyDB", "temp", "127.0.0.1"); Copy the MyDB data of this machine to the TEMP database 7, repair the current database  db.repairdatabase (); 8. View the database currently in use &NBSp;db.getname ();  db; The DB and GetName methods are the same effect, can query the currently used database 9, display the current DB status  db.stats (); 10, the current DB version  db.version (); 11, view the current DB link machine address  db.getmongo ();   Collection Aggregation collection   1, create a clustered collection (table)  db.createcollection ("Collname", {size:20, Capped:5, max:100}); 2. A clustered Set (table)  db.getcollection ("account") with the specified name; 3, get all the current DB aggregation set  db.getcollectionnames (); 4, display the current DB all Clustered index status  db.printcollectionstats ();   User-related   1, add a user  db.adduser ("name");  db.adduser ("UserName", "pwd123", true); Add user, set password, whether read only 2, database authentication, security mode  db.auth ("UserName", "123123"); 3. Display all current user  show users; 4, delete user  db.removeuser ("UserName");   Other   1, the error message before the query  db.getpreverror (); 2, clear Error Record  db.reseterror ();     View aggregate collection basic information   1, view Help Db.yourColl.help (); 2, query the current collection of data bar number Db.yourColl.count (); 3, view data space size db.userInfo.dataSize (); 4. Get the DB Db.userInfo.getDB () where the current aggregation set resides; 5, get the current gathering state db.userInfo.stats (); 6, get the aggregate aggregate size db.userInfo.totalSize (); 7. Aggregate storage space Size db. Userinfo.storagesize (); 8, shard version Information Db.userInfo.getShardVersion () 9, Aggregation set rename Db.userInfo.renameCollection ("Users"); Rename UserInfo to users 10, delete the current clustered collection Db.userInfo.drop ();   Gather collection query   1, query all Records db.userInfo.find (); Equivalent: select* from UserInfo; The default is 20 records per page, and you can query the next page of data with the IT iteration command when the display is not displayed. Note: Type the IT command cannot take ";" but you can set the size of the data displayed per page, with dbquery.shellbatchsize= 50, so that each page shows 50 records.   &NBSP;2, the duplicate data db.userInfo.distinct ("name") of a column in the current clustered collection after the query is stripped; Will filter out the same data in name equivalent to: Select Distict name from UserInfo;    3, query age = 22 Record Db.userInfo.find ({"Age": 22}); Equivalent to: SELECT * from userInfo where age = 22;    4, query age > 22 record Db.userInfo.find ({age: {$gt: 22}}); Equivalent to: SELECT * from UserInfo where >22;    5, query age < 22 record Db.userInfo.find ({age: {$lt: 22}}); Equivalent to: SELECT * from UserInfo where <22;    6, querying the record Db.userInfo.find ({age: {$gte: 25}}) of age >= 25; Equivalent to: SELECT * from UserInfo where age >= 25;    7, querying the record Db.userInfo.find ({age: {$lte: 25}}) of age <= 25; &nbSp  8, Query age >= 23 and age <=-Db.userInfo.find ({age: {$gte:, $lte: 26}});    9, query name contains MONGO data Db.userInfo.find ({name:/mongo/}); Equivalent to a percent of select * from UserInfo where the name like '%mongo% ';    10, query name Db.userInfo.find ({name:/^mongo/}) starting with MONGO; SELECT * from UserInfo where name is like ' mongo% ';   &NBSP;11, query the specified column name, age data Db.userInfo.find ({}, {name:1, age:1}); Equivalent to: Select Name, age from UserInfo; Of course name can also be used with true or false, as in the case of Ture River Name:1 effect, if False is to exclude name, display column information other than name.   &NBSP;12, query the specified column name, age data, age > Db.userInfo.find ({age: {$gt: +}}, {name:1, age:1}); Equivalent to: Select Name, age from UserInfo where age >25;    13, sorted by age Ascending: Db.userInfo.find (). Sort ({age:1}); Descending: Db.userInfo.find (). Sort ({Age:-1});    14, query name = Zhangsan, age = 22 Data db.userInfo.find ({name: ' Zhangsan ', age:22}); Equivalent to: SELECT * from userInfo where name = ' Zhangsan ' and "age = ' 22 ';   &NBSP;15, query the first 5 data db.userInfo.find (). Limit (5); Equivalent: Selecttop 5 * FROM UserInfo;    16, query after 10 data db.userInfo.find (). Skip (10); Equivalent to: SELECT * from UserInfo where ID not in (selecttop * from UserInfo);   &NBSP;17, querying data between 5-10 db.userInfo.find (). Limit (.). Skip (5); Can be used for pagination, limit is Pagesize,skip is the page *pagesize    18, or with query Db.userInfo.find ({$or: [{age:22}, {age:25}]}); Equivalent to: SELECT * from UserInfo where is age = 25   &NBSP;19, query the first Data Db.userInfo.findOne (); Equivalent: Selecttop 1 * from UserInfo; Db.userInfo.find (). limit (1);   &NBSP;20, query the number of record bars for a result set Db.userInfo.find ({age: {$gte: +}}). Count (); Equivalent to: SELECT COUNT (*) from UserInfo where age >= 20;    21, sort by a column db.userInfo.find ({* * *: {$exists: true}}). Count (); Equivalent to: SELECT COUNT (* * *) from UserInfo;   Index   1, CREATE index Db.userInfo.ensureIndex ({name:1}); Db.userInfo.ensureIndex ({name:1, TS:-1});   &NBSP;2, queries the current aggregation collection All Indexes db.userInfo.getIndexes ();    3, view total index record size db.userInfo.totalIndexSize ();    4, reads all index information for the current collection Db.users.reIndex (); &nBsp &NBSP;5, delete the specified index Db.users.dropIndex ("Name_1");   &NBSP;6, delete all indexed indexes db.users.dropIndexes ();     Modify, add, delete collection data   1, add Db.users.save ({name: ' Zhangsan ', age:25, * *: true}); The data column of the added data is not fixed, according to the added data is quasi    2, modify Db.users.update ({age:25}, {$set: {name: ' ChangeName '}}, False, True); Equivalent to: Update users set name = ' ChangeName ' where age = 25;    db.users.update ({name: ' Lisi '}, {$inc: {age:50}}, False, True); Equivalent to: Update users set age = Age + where name = ' Lisi ';    db.users.update ({name: ' Lisi '}, {$inc: {age:50}, $set: {name: ' HoHo '}}, False, True); Equivalent to: Update users set age = Age +, name = ' HoHo ' WHERE name = ' Lisi ';    3, delete db.users.remove ({age:132});    4, query Modify Delete db.users.findAndModify ({  query: {age: {$gte: +}},    sort: {Age:-1},   &NBSP ; Update: {$set: {name: ' A2 '}, $inc: {age:2}},   remove:true});    db.runcommand ({findandmodify: "Users",    query: {age: {$gte: 25}},    sort: {Age:-1},    update: {$set: {name: ' A2 '}, $inc: {age:2}},   remove:true}); Update or remove one of them is a required parameter; Additional parameters are optional. Parameter details default query filter condition {} Sort if multiple documents conform to the query filter criteria, the object will be selected in the first place in the arrangement specified by the parameter, and the object is to be manipulated {} If True, the selected object will be deleted before it is returned N/a update Modifier object N/A new if True, the modified object is returned instead of the original object. In the delete operation, the parameter is ignored. False fields see retrieving a subset of fields (1.5.0+) All fields Upsert Create a new object if the query result is empty. Example (1.5.4+) False   statement block Operation   1, simple Hello World print ("Hello world!"); This notation calls the print function, and writes "Hello world!" directly The effect is the same;    2, converts an object to JSON Tojson (new object ()); Tojson (New Object (' a '));    3, loop Add Data > for (var i = 0; i < i++) {... db.users.save ({name: "u_" + I, age:22 + i, * *: I% 2}); ... }; This adds 30 data to the loop, and can also omit the notation for parentheses > for (var i = 0; i < i++) Db.users.save ({name: "u_" + I, age:22 + i, * * *: I% 2}); is also possible, when you use Db.users.find () query, display multiple data and can not be displayed on a page, the use of it to view the next page of information;   &NBSP;4, find cursor query >var cursor = Db.users.find (); > while (cursor.Hasnext ()) {   printjson (Cursor.next ());  } so you can query all the users information, as well as the var cursor = Db.users.find (); while (Cursor.hasnext ()) {Printjson (cursor.next);} You can also omit the {}    5, foreach iteration Loop Db.users.find (). foreach ( Printjson); A function must be passed in foreach to handle the data information for each iteration    6, and the find cursor is treated as an array of var cursor = Db.users.find (); CURSOR[4]; The data that gets the subscript index of 4 can be processed as an array, and the length of it can be obtained: Cursor.length (); or cursor.count (); That way we can also display the data for (var i = 0, Len = c.length (), I < Len, i++) Printjson (C[i]) in the loop.   &NBSP;7, convert find cursor to array > var arr = db.users.find (). ToArray (); > Printjson (arr[2]); Use the ToArray method to convert it to arrays    8, customize our own query results to show only age <= 28 and only show the age of this column of data Db.users.find ({age: {$lte: +}}, {age:1}). ForEach (Printjson); Db.users.find ({age: {$lte: +}}, {age:true}). ForEach (Printjson); Excludes Age's Column db.users.find ({age: {$lte: +}}, {Age:false}). ForEach (Printjson);    9, foreach transfer function displays information Db.things.find ({x:4}). foreach (function (x) {print (Tojson (x));});  


Installation and operation of MongoDB under Linux

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.