MongoDB Learning (ii) MONGODB common commands

Source: Internet
Author: User
Tags create index tojson

One, DB data operation

    (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 to            query all databases      show DBS;             (4) Delete the currently used database      db.dropdatabase ();             (5) Cloning the database      db.clonedatabase ("127.0.0.1") from the designated host      ; Clones data from the database on the specified machine to the current database             (6) Copy 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) to fix the current database      db.repairdatabase ();             (8) View the currently used database      db.getname ();      DB;      The DB and GetName methods are the same effect and can query the currently used database             (9) to display the current DB status      db.stats ();             (10) Current DB version      db.version ();             (11) View the current DB link machine address      db.getmongo ();  

2. 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 aggregation sets of the current DB      db.getcollectionnames ();             (4) Displays the status of all clustered indexes of the current DB      db.printcollectionstats ();  

3. User-related

    (1) Add a user      Db.adduser ("name");      Db.adduser ("UserName", "pwd", true); #用户, password, whether read            -only (2) database authentication, security mode      Db.auth ("UserName", "pwd");            (3) Show all current user show users      ;             (4) Delete user      Db.removeuser ("UserName");  

4. Other

    (1) Error message before query      db.getpreverror ();             (2) Clear Error Record      db.reseterror ();  

Second, collection aggregation set operation

1. View aggregate Collection basic information

    Db.yourColl.help (); #查看帮助      Db.yourColl.count (); #查询当前集合的数据条数      db.yourColl.dataSize (); #查看数据空间大小      Db.yourColl.getDB (); Get the DB Db.yourColl.stats () of the current aggregation set,      #得到当前聚集的状态      db.yourColl.totalSize (); #得到聚集集合总大小      Db.yourColl.storageSize (); #聚集集合储存空间大小      db.yourColl.getShardVersion (); #Shard版本信息      db.yourColl.renameCollection ("users"); #聚集集合重命名      Db.yourColl.drop (); #删除当前聚集集合  

2. Aggregate collection queries

    (1) query all Records db.userInfo.find ();      Equivalent to: 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.      (2) Duplicate data db.userInfo.distinct ("name") for a column in the current 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 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 the record Db.userInfo.find ({age: {$gte: 25}) of age >= 25;             Equivalent to: SELECT * from UserInfo where age >= 25;             (7) Query the record Db.userInfo.find ({age: {$lte: 25}) of age <= 25; (8) Query age >= 23 and age <=-Db.userInfo.find ({age: {$gte: $, $lte: 26}});      (9) The 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 the name Db.userInfo.find ({name:/^mongo/}) beginning 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;             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.      (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 ';      (15) Query the first 5 data db.userInfo.find (). Limit (5); Equivalent to: SELECT Top 5 * from UserInfo;      (16) Query 10 after the data Db.userInfo.find (). Skip (10);             Equivalent to: SELECT * from UserInfo where ID not in (select Top ten * from UserInfo);      (17) query data between 5-10 db.userInfo.find (). Limit (Ten). Skip (5);      Can be used for pagination, limit is Pagesize,skip is the number of pages *pagesize () or with the query Db.userInfo.find ({$or: [{age:22}, {age:25}]});             Equivalent to: SELECT * from UserInfo where is age = 25      (19) Query the first Data Db.userInfo.findOne ();      Equivalent: SELECT top 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 to: SELECT COUNT (*) from UserInfo where age >= 20;      (+) exists db.userInfo.find ({sex: {$exists: true}}). Count ();   Equivalent to: SELECT COUNT (Sex) from userInfo;

3. Index

    (1) CREATE index      db.userInfo.ensureIndex ({name:1});      Db.userInfo.ensureIndex ({name:1, TS:-1});             (2) Query the current aggregate collection all Indexes      db.userInfo.getIndexes ();             (3) View total index record size      db.userInfo.totalIndexSize ();             (4) Read all index information of the current set      db.users.reIndex ();             (5) Delete the specified index      db.users.dropIndex ("Name_1");             (6) Delete all Index index      db.users.dropIndexes ();  

4. Modify, add, and delete collection data

    (1) Add Db.users.save ({name: ' Zhangsan ', age:25, sex:true});      The data column of the added data is not fixed, according to the added data (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 modification 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 '}, $inc: {age:2}},         Remove:true});   

  Third, 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) Convert an object to a 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, sex:i% 2});      };      This adds 30 data to the loop, and can also omit the notation for (var i = 0; i < i++) Db.users.save ({name: "u_" + I, age:22 + i, sex:i% 2}); It 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; (4) Find cursor query var cursor = DB.USERS.F      IND ();       while (Cursor.hasnext ()) {Printjson (Cursor.next ());      This will 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 {} number (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) The Find cursor is treated as an array of var cursor = Db.users.find ();      CURSOR[4]; The data that gets the subscript index 4 is now availableTo be treated as an array, 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.      (7) Convert the Find cursor to the tuple var arr = Db.users.find (). ToArray ();      Printjson (arr[2]); Use the ToArray method to convert it to an array (8) Customizing our own query results to show only age <= 28 and only 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) The Foreach transfer function displays information Db.things.find ({x:4}). foreach (function (x) {print (Tojson (x));});   As described above, foreach needs to pass a function that takes a parameter, that is, the object that is currently looping, and then processes the incoming parameter information in the function weight.

MongoDB Learning (ii) MONGODB common commands

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.