Simple installation and basic operation of MongoDB under Linux system _mongodb

Source: Internet
Author: User
Tags create index gz file mongodb mongodb server tojson create database port number

Mongo DB is a kind of non relational database (NOSQL) which is very popular in the IT industry, and its flexible data storage is favored by current it practitioners. Mongo db is a good way to implement object-oriented thinking (OO), where each record in Mongo DB is a document object. The biggest advantage of Mongo DB is that all data persistence operations require no developer to manually write SQL statements, and the direct invocation of the method makes it easy to implement CRUD operations.

First, download MongoDB

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

But a little pit dad is, the download link is clearly tgz format, the results of the download into the GZ format:

Let's download and see.

Second, decompression MongoDB

[Root@test6 ~]# gzip-d mongodb-linux-x86_64-2.6.4.gz

Get is mongodb-linux-x86_64-2.6.4, incredibly is a file, not a folder, and the Internet said very different:


It seems that the previous download of the problem is indeed! In fact, should be the tgz file, according to experience analysis, download the actual or tgz file, shown as GZ file is just the form of illusion! So gzip only extracts the outer layer of the compressed package, and actually needs to extract the Tar archive attribute!

The extracted file is then renamed with the TAR format:

[Root@test6 ~]# MV mongodb-linux-x86_64-2.6.4 Mongodb-linux-x86_64-2.6.4.tar

Then, use tar to decompress:

[Root@test6 ~]# tar xvf mongodb-linux-x86_64-2.6.4.tar

Move & Rename the unpacked folder to/usr/local/mongodb

[Root@test6 ~]# mv Mongodb-linux-x86_64-2.6.4/usr/local/mongodb
[root@test6 ~]# cd/usr/local/mongodb/bin/
[ Root@test6 ~]# LL

Bin Mongod is the MongoDB server process, MONGO is its client, other commands for MongoDB other uses such as MongoDB file export.

Third, start MongoDB
before starting, specify the MongoDB data directory, and if not, create one:

[Root@test6 ~]# cd/usr/local/mongodb
[root@test6 mongodb]# mkdir data

You can then start MongoDB by executing the following command:

[Root@test6 mongodb]#/usr/local/mongodb/bin/mongod--dbpath=/usr/local/mongodb/data/--logpath=/usr/local/mongodb /data/mongodb.log--logappend&

After successful startup, you can see if the startup is successful, the default port number is 27017, and you can also specify unused ports at startup.

Finally, the client Mogo file under the/bin soft link, easy to execute everywhere:

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

Now use the MONGO client to access the database:

[Root@test6 bin]#./mongo
MongoDB Shell version:2.6.4 connecting to:test
>

Installation Successful!

Four, attached: basic operation

Basic usage of MongoDB database show DBS: Displaying a list of databases show collections: Displaying collections in the current database (similar to tables in relational databases) Show Users: Display user use <db Name&gt: Toggle the current database, which 
It's the same as the ms-sql inside. Db.help (): Display database operation commands, there are a lot of commands db.foo.help (): Display set operation commands, there are also a lot of commands, Foo refers to the current database, a collection called Foo, not the true meaning of the 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}): Find the Foo collection in the current database, if there is a property called a in the data and a value of 1
MongoDB does not have a command to create the database, but has a similar command.
For example, if you want to create a "myTest" database, run the use MyTest command, and then do something (such as db.createcollection (' user '), so you can create a database called "myTest."
 Database Common Command 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 is automatically created 3, all database show DBs are queried;
4, delete the current use of the database Db.dropdatabase (); 5, from the designated host Clone Database Db.clonedatabase ("127.0.0.1");
Clones data from the database on the specified machine to the current database 6, replicates the specified database data from the specified machine to a database Db.copydatabase ("MyDB", "temp", "127.0.0.1"), and copies the MyDB data from the computer to the TEMP database
7, repair the current database db.repairdatabase ();
 8, view the current use of the database Db.getname (); db
DB and GetName methods are the same effect, you can query the currently used database 9, display the current DB State db.stats ();
10, the current DB version db.version (); 11,View the current DB link machine address Db.getmongo ();
Collection aggregation set 1, create a aggregation set (table) db.createcollection ("Collname", {size:20, Capped:5, max:100});
2, get the specified name of the aggregation set (table) Db.getcollection ("account");
3, get the current db of all the 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, read only 2, database authentication, Safe Mode Db.auth ("UserName", "123123");
3. Show users of all current user;

4, delete the user db.removeuser ("UserName");
Other 1, the error message before the query Db.getpreverror ();
 
2, clear Error Record db.reseterror ();
View the Aggregate collection Profile 1, view Help Db.yourColl.help ();
2, query the current set of data bar number Db.yourColl.count ();
3, view the size of the data Space db.userInfo.dataSize ();
4. Get the DB Db.userInfo.getDB () where the current aggregation set is located;
5, get the current aggregation state db.userInfo.stats ();
6, get the aggregate aggregate size db.userInfo.totalSize ();
7, the aggregation set 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 aggregation set Db.userInfo.drop ();
Aggregate collection Query 1, query all Records db.userInfo.find ();
Equivalent to: select* from UserInfo; Default perThe page displays 20 records, and when it does not appear, you can query the next page of data with it iteration commands.
 
Note: type it commands without ";" but you can set the size of each page to display the data, with dbquery.shellbatchsize= 50, so that each page shows 50 records.
2. Duplicate data db.userInfo.distinct ("name") of a column in the current clustered collection after the query is removed;
 
Will filter out the same data in name equivalent to: Select Distict name from UserInfo;
3, Query age = 22 Records Db.userInfo.find ({"Age": 22});
 
Equivalent to: SELECT * from userInfo where age = 22;
4, Query age > 22 Records db.userInfo.find ({age: {$gt: 22}});
 
Equivalent to: SELECT * from UserInfo where age >22;
5, Query Age < 22 Records Db.userInfo.find ({age: {$lt: 22}});
 
Equivalent to: SELECT * from UserInfo where age <22;
6, Query age >= 25 Records Db.userInfo.find ({age: {$gte: 25}});
 
Equivalent to: SELECT * from UserInfo where age >= 25;
 
7, Query age <= 25 Records Db.userInfo.find ({age: {$lte: 25}});
 
8, query Age >= 23 and age <= Db.userInfo.find ({age: {$gte:, $lte: 26}});
9, query name contains MONGO data Db.userInfo.find ({name:/mongo/});
 
Equal to the% select * from UserInfo where name is like '%mongo% ';
10. Db.userInfo.find ({name:/^mongo/}) Beginning with MONGO in Query name;
 
SELECT * from UserInfo where name like ' mongo% '; 11, query specified column nAME, age data Db.userInfo.find ({}, {name:1, age:1});
Equivalent to: Select Name, age from UserInfo;
 
Of course, name can also use True or false, as with ture in the case of river Name:1 effect, if False is excluding name, display column information other than name.
12. Query specifies 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 ';
15, query the first 5 data db.userInfo.find (). Limit (5);
 
Equivalent to: Selecttop 5 * from UserInfo;
16, after the query 10 data db.userInfo.find (). Skip (10);
 
Equivalent to: SELECT * from UserInfo where ID not in (selecttop to UserInfo);
17, the query in the data between 5-10 db.userInfo.find (). Limit (a). Skip (5);
Available for pagination, limit is Pagesize,skip *pagesize 18, OR and query Db.userInfo.find ({$or: [{age:22}, {age:25}]});
 
Equivalent to: SELECT * from userInfo where age = 25;
19, query the first Data Db.userInfo.findOne (); Equivalent to: selecttop1 * from UserInfo;
 
Db.userInfo.find (). limit (1);
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, according to a column to sort db.userInfo.find ({* * *: {$exists: true}}). Count ();

Equivalent: SELECT COUNT (* * *) from UserInfo;
Index 1, CREATE index Db.userInfo.ensureIndex ({name:1});
 
Db.userInfo.ensureIndex ({name:1, TS:-1});
 
2, query the current aggregate collection of all Indexes db.userInfo.getIndexes ();
 
3, view the total index record size db.userInfo.totalIndexSize ();
 
4, read the current collection of all index information db.users.reIndex ();
 
5, delete the specified index Db.users.dropIndex ("Name_1");
 
6, delete all Index index 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, no 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: 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 modification Delete db.users.findAndModify ({query: {age: {$gte:}}, Sort: {Age:-1}, Update: {$set: {name: ' A2 '}, $inc: {A
 
Ge:2}}, remove:true}); Db.runcommand ({findandmodify: "Users", query: {age: {$gte:}}, Sort: {Age:-1}, Update: {$set: {name: ' A2 '},
$inc: {age:2}}, remove:true}); Update or remove one of the necessary parameters;
Other parameters are optional. Parameter details default query filter criteria {} Sort if multiple documents meet the query filtering criteria, the object that is ranked first in the arrangement specified by the parameter is selected and the object will be manipulated {} Remove if True, the selected object will be deleted before returning N/a update The Modifier object n/A new, if true, returns the modified object instead of the original object.
In a delete operation, this 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 type of writing invokes the print function, and writes directly to "Hello world!"
The effect is the same; 2, converts an object to a JSON Tojson (new object ());
 
Tojson (New Object (' a ')); 3. Recycle Add Data > for (var i = 0; i < i++) {... db.users.save ({name: "u_" + I, age:22 + i,: I% 2});
... };
This loops the addition of 30 of data, and can also omit the notation of 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 more than one page of data, you can use it to view the next page of information; 4, find cursor query >var cursor = Db.users.find (); 
> while (Cursor.hasnext ()) {Printjson (Cursor.next ());
This allows you to query all the users information, as well as write var cursor = Db.users.find ();
while (Cursor.hasnext ()) {Printjson (cursor.next);} can also omit {} number 5, foreach Iteration Loop Db.users.find (). foreach (Printjson);
foreach must pass a function to process the data information of each iteration 6, the Find cursor when the array processing var cursor = Db.users.find ();
CURSOR[4];
The data that gets the subscript index 4, since it can be treated as an array, can get its length: cursor.length (); or cursor.count ();
 
So we can also use the loop to display the data for (var i = 0, Len = c.length (); i < Len; i++) Printjson (c[i));
7. Convert find cursor to group > var arr = db.users.find (). ToArray ();
> Printjson (arr[2]); Convert it to array 8 with the ToArray method, customize our own query results show only age <= 28 and show only age this column of data Db.users.find ({age: {$lte:}}, {age:1}). ForEach (Printjs
ON); Db.users.find ({age: {$lte:}}, {age:true}). ForEach (Printjson);
 
Exclude Age Column Db.users.find ({age: {$lte:}}, {Age:false}). ForEach (Printjson); 9. The Foreach transfer function displays the information Db.things.find ({x:4}). foreach (function (x) {print (Tojson (x));});

Reference article ①:http://blog.csdn.net/ssyan/article/details/6927307

Reference article ②:http://blog.chinaunix.net/uid-26558059-id-3211264.html

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.