MongoDB installation, operation

Source: Internet
Author: User
Tags create index tojson

A. MongoDB installation

1.1 Download the installation package

wget http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel55-3.2.0.tgz

1.2 Unzip, move to/usr/local/mongodb directory

TAR-ZXVF Mongodb-linux-x86_64-rhel55-3.2.0.tgzsudo MV Mongodb-linux-x86_64-rhel55-3.2.0/usr/local/mongodb

1.3 Directory Description

Cd/usr/local/mongodb

1.3.1 Directory Bin

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

Create a soft link so that it can be easily executed

sudo ln-s/usr/local/mongodb/bin/mongod/usr/local/bin/mongodsudo ln-s/usr/local/mongodb/bin/mongo/usr/local/bin/ Mongo

1.3.2 Data Directory

If there is no data directory, create a new data directory

mkdir data

1.4 Start MongoDB

Mongod--dbpath=/usr/local/mongodb/data/--logpath=/usr/local/mongodb/data/mongodb.log--logappend&

After startup, the default port is 27017, which detects

1.5 Starting the Client

$sudo Mongomongodb Shell version:3.2.0connecting to:test
Two. Operation
Show DBS: Display database list Show Collections: Displays a collection in the current database (similar to a table in a relational database) show Users: Show user use <db Name>: Switch the current database, which is the same as Ms-sql. Db.help (): Show Database Operations Command, there are a lot of commands db.foo.help (): Display set operation command, also have a lot of commands, Foo refers to the current database, a set called Foo, not the real 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}): Finds the Foo collection in the current database, provided that there is a property called a in the data. And A has a value of 1MongoDB there is no command to create the database, but there is 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 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 3 is automatically created, query all databases show dbs;4, delete the currently used database Db.dropdatabase (), 5, clone the database from the specified 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 from the native to the TEMP database 7, repair the current database Db.repairdatabase (), 8, view the currently used database 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 Gather collection 1, create a clustered set(table) db.createcollection ("Collname", {size:20, Capped:5, max:100}), 2, a clustered collection (table) with the specified name Db.getcollection (" Account "), 3, obtains all the current DB aggregation set Db.getcollectionnames (), 4, displays 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, Safe Mode Db.auth ("UserName", "123123"), 3, show all current user show users;4, delete user db.removeuser ("UserName");  Other 1, the error message before the query Db.getpreverror (); 2, clear the Error Record db.reseterror (); View aggregate collection basic information 1, view Help Db.yourColl.help (), 2, query the current collection of data Db.yourColl.count (), 3, view data space size db.userInfo.dataSize (), 4, Get the current collection of DB Db.userInfo.getDB (), 5, get the current aggregation state db.userInfo.stats (), 6, get the aggregate aggregate size db.userInfo.totalSize (); 7, Aggregate collection storage size db.userInfo.storageSize (); 8, shard version Information Db.userInfo.getShardVersion () 9, clustered collection rename Db.userInfo.renameCollection ("users"); Rename the UserInfo to Users10, delete the current clustered collection Db.userInfo.drop (); Aggregate collection Query 1, query all Records db.userInfo.find (); equivalent: select* from UserInfo; The default is 20 records per page, and when not shown, you can query the next page of data with it iteration commands. Note: Type the IT command cannot take ";" but you can set the size of the data displayed per page, with dbquery.shellbatchsize= 50;Each page is displayed with 50 records.  2. The duplicate data db.userInfo.distinct ("name") of a column in the current collection after the query is removed; the same data in name is filtered out to the same amount: 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 age >22;  5. Query age < 22 record Db.userInfo.find ({age: {$lt: 22}}), equivalent to: SELECT * from UserInfo where age <22;  6. Query Db.userInfo.find ({age: {$gte: 25}) for the record of age >= 25, equivalent to: SELECT * from UserInfo where the age >= 25;  7, Query the age <= 25 record Db.userInfo.find ({age: {$lte: 25}});  8. Query age >= 23 and age <= 26db.userinfo.find ({age: {$gte: $, $lte: 26}});  9. Query name contains MONGO data Db.userInfo.find ({name:/mongo/});//equivalent to%%select * from UserInfo where name like '%mongo% ';  10. Query name Db.userInfo.find ({name:/^mongo/}) Starting with MONGO, select * from UserInfo where name is like ' mongo% '; 11. Query the specified column name, age data Db.userInfo.find ({}, {name:1, age:1}), equivalent to: select Name, age from UserInfo, and of course name can also use True or FALSE, When using Ture, the river name:1 the same effect., if you use False to exclude name, display column information other than name. 12. Query the specified column name, age data, age > 25db.userinfo.find ({age: {$gt: +}}, {name:1, age:1}), equivalent to: select Name, age from UserInfo WH  Ere age >25;  13. Sort Ascending by Age: 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: SELECT * from userInfo where name = ' en  Angsan ' and age = ' 22 ';  15, query the first 5 data db.userInfo.find (). Limit (5); equivalent: selecttop 5 * from UserInfo;  16, the query 10 after the data Db.userInfo.find (). Skip (10); equivalent: SELECT * from UserInfo where ID not in (selecttop * from UserInfo); 17, query the data between 5-10 db.userInfo.find (). Limit (5); can be used for pagination, limit is Pagesize,skip is the first few pages *pagesize 18, OR and  Query Db.userInfo.find ({$or: [{age:22}, {age:25}]}), equivalent to: SELECT * from UserInfo where is age = n or age = 25;  19, query the first Data Db.userInfo.findOne (); equivalent to: Selecttop 1 * 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: SELECT COUNT (*) from userInfo where >= 20; 21. Sort by a column db.userInfo.find ({* *: {$exists: true}}). count (); equal to: SELECT COUNT (* * *) from UserInfo;  Index 1, CREATE index Db.userInfo.ensureIndex ({name:1});d B.userinfo.ensureindex ({name:1, TS:-1});  2, query the current aggregate collection all Indexes db.userInfo.getIndexes ();  3, view the total index record size db.userInfo.totalIndexSize ();  4, read all index information of the current collection 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}), data column of the added data, not fixed, according to the added data is 2, modify Db.users.update ({  Age:25}, {$set: {name: ' ChangeName '}}, False, True); equivalent: 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: Update users set age = Age + 50  , 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}, Update: {$set: {name: ' A2 '}, $inc: {age:2}}, remove:true}); Db.runcommand ({findandmodify: "Users", query: {age: {$gte: +}}, Sort: {Age:-1}, Update: {$set: {name: ' A2 '}, $in C: {Age:2}}, remove:true}); Either update or remove 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 that is ranked first is selected in the arrangement specified by the parameter, and the object will be manipulated {}remove If True, the selected object will be deleted before it is returned n/aupdate a Modifier Object N/anew If True, the modified object is returned instead of the original object. In the delete operation, the parameter is ignored. Falsefields see retrieving a subset of fields (1.5.0+) All Fieldsupsert Create a new object if the query result is empty. Example (1.5.4+) false statement block operation 1, simple Hello worldprint ("Hello world!"); This notation calls the print function, and writes "Hello world!" directly  The effect is the same; 2. Convert an object to Jsontojson (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}); Yes, you can use it to view the next page of information when you are querying with db.users.find () and displaying multiple data without a single page display; 4, find cursor query >var cursor = Db.useRs.find ();> while (Cursor.hasnext ()) {Printjson (Cursor.next ());} In this way, all the users information is queried, as can the var cursor = Db.users.find (), while (Cursor.hasnext ()) {Printjson (cursor.next);} You can also omit the {} number 5, foreach Iteration Loop Db.users.find (). foreach (Printjson); foreach must pass a function to handle the data information for each iteration 6, the Find cursor when the array handles the VAR cursor = Db.users.find (); cursor[4]; If you get the index of subscript 4, the data can be treated as an array, then it can be obtained in length: 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. 7. Convert the Find cursor to an array of > var arr = db.users.find (). ToArray ();> Printjson (arr[2]); convert it to array 8 using the ToArray method, customizing our own query results to show only the age <= 28 and displays only the age of this column of data Db.users.find ({age: {$lte: +}, {age:1}). ForEach (Printjson);d B.users.find ({age: {$lte: 28}}, {  Age:true}). foreach (Printjson); Excludes the Age column Db.users.find ({age: {$lte: +}}, {Age:false}). foreach (Printjson); 9. The Foreach transfer function displays information Db.things.find ({x:4}). foreach (function (x) {print (Tojson (x));});

  

MongoDB installation, operation

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.