Basic usage of MongoDB

Source: Internet
Author: User
Tags tojson
basic MongoDB database usage Show DBS: displays the Database List show collections: displays the sets in the current database (similar to tables in relational databases) show users: displays the user use <dB Name>: switches the current database, this is the same as the meaning in MS-SQL dB. help (): displays database operation commands. There are many commands in the database. foo. help (): displays the set operation commands. There are also many commands. Foo refers to a set named Foo in the current database, rather than a real command dB. foo. find (): searches for the foo set in the current database (all data is listed due to no conditions) dB. foo. find ({A: 1}): searches for the foo set in the current database. The condition is that there is an attribute named a in the data, and the value of A is 1. MongoDB has no database creation command, but there are similar commands. For example, if you want to create a database named "mytest", run the use mytest command first and then perform some operations (such as DB. createcollection ('user') to create a database named "mytest. Common database commands 1. Help Command Prompt help dB. help (); dB. yourcoll. help (); dB. youcoll. find (). help (); RS. help (); 2. Switch to/create database use yourdb; When a set (table) is created, the current database is automatically created. 3. query all databases; 4. Delete the currently used database. dropdatabase (); 5. Clone the database DB from the specified host. clonedatabase ("127.0.0.1"); clone the database data on the specified machine to the current database 6. copy the data from the specified machine to a database. copydatabase ("mydb", "Temp", "127.0.0.1"); copy the mydb data of the local machine to the temp database. 7. Fix the current database. repairdatabase (); 8. view the currently used database. getname (); dB; the DB and getname methods have the same effect. You can query the currently used database 9 and display the current dB status. stats (); 10. Current DB version. version (); 11. view the address of the linked machine dB of the current dB. getmongo (); Collection aggregation set 1. Create an aggregation set (table) dB. createcollection ("collname", {size: 20, capped: 5, Max: 100}); 2. Get the clustered set (table) dB with the specified name. getcollection ("account"); 3. obtain all the clustered dB of the current dB. getcollectionnames (); 4. display the status of all clustered indexes of the current dB. printcollectionstats (); User-related 1. Add a user database. adduser ("name"); dB. adduser ("username", "pwd123", true); add a user, set a password, whether to read-only 2, database authentication, security mode dB. auth ("username", "123123"); 3. Show all current users; 4. delete user dB. removeuser ("username "); Others 1. query the previous error message dB. getpreverror (); 2. Clear the error record DB. reseterror (); View basic information about a collection   1. view the help database. yourcoll. help (); 2. query the number of data entries in the current set. yourcoll. count (); 3. view the data space size dB. userinfo. datasize (); 4. Obtain the DB where the current collection is located. userinfo. getdb (); 5. Get the status dB of the current cluster. userinfo. stats (); 6. Get the total size of the clustered set dB. userinfo. totalsize (); 7. Size of the storage space of the aggregation set dB. userinfo. storagesize (); 8. Shard version information dB. userinfo. getshardversion () 9. Rename the database for the clustering set. userinfo. renamecollection ("users"); rename userinfo to users10, delete the current collection dB. userinfo. drop (); Aggregate collection Query   1. query all record databases. userinfo. find (); equivalent to: Select * From userinfo; by default, 20 records are displayed on each page. If no record is displayed, you can use it iteration commands to query data on the next page. Note: you cannot enter ";" for the IT command, but you can set the size of data displayed on each page. Use dbquery. shellbatchsize = 50. In this way, 50 records are displayed on each page. 2. query the duplicate data dB of a column in the current clustering set after removal. userinfo. distinct ("name"); will filter out the same data in the name is equivalent to: Select distict name from userinfo; 3. query the record DB with age = 22. userinfo. find ({"Age": 22}); equivalent to: Select * From userinfo where age = 22; 4. query the record DB of age> 22. userinfo. find ({age: {$ GT: 22}); equivalent to: Select * From userinfo where age> 22; 5. query the record DB of age <22. userinfo. find ({age: {$ LT: 22}); equivalent to: Select * From userinfo where age <22; 6. query the record DB with age> = 25. use Rinfo. find ({age: {$ GTE: 25}); equivalent to: Select * From userinfo where age> = 25; 7. query the record DB of age <= 25. userinfo. find ({age: {$ LTE: 25}); 8. query age> = 23 and age <= 26db. userinfo. find ({age :{$ GTE: 23, $ LTE: 26}); 9. query the data dB whose name contains Mongo. userinfo. find ({Name:/Mongo/}); // equivalent to % select * From userinfo where name like '% Mongo %'; 10. query the DB whose name starts with Mongo. userinfo. find ({Name:/^ Mongo/}); select * From userinfo where name l Ike 'mongo % '; 11. query the specified column name and age data dB. userinfo. find ({}, {Name: 1, age: 1}); equivalent to: Select name, age from userinfo; of course, name can also be true or false, if true is used, the effect of name: 1 is the same. If false is used, the column information other than name is displayed. 12. query the name and age data of a specified column. age> 25db. userinfo. find ({age: {$ GT: 25 }}, {Name: 1, age: 1}); equivalent to: Select name, age from userinfo where age> 25; 13. sort by age in ascending order: DB. userinfo. find (). sort ({age: 1}); descending order: DB. userinfo. find (). sort ({age:-1}); 14. query the data dB with name = zhangsan and age = 22. userinfo. find ({Name: 'hangsan', age: 22}); equivalent to: Select * From userinfo where name = 'hangsan' and age = '22 '; 15. query the first five databases. userinfo. find (). limit (5); equivalent to: selecttop 5 * From userinfo; 16. Query 10 databases. userinfo. find (). skip (10); equivalent to: Select * From userinfo where id not in (selecttop 10 * From userinfo); 17. query the data dB between 5 and 10. userinfo. find (). limit (10 ). skip (5); used for paging, limit is pagesize, Skip is the page * pagesize 18, or and query DB. userinfo. find ({$ or: [{age: 22}, {age: 25}]}); equivalent to: Select * From userinfo where age = 22 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 records in a result set. userinfo. find ({age :{$ GTE: 25 }}). count (); equivalent to: Select count (*) from userinfo where age> = 20; 21. Sort dB by a column. userinfo. find ({***: {$ exists: true }}). count (); equivalent to: Select count (***) from userinfo; Index 1. Create an index database. userinfo. ensureindex ({Name: 1}); dB. userinfo. ensureindex ({Name: 1, TS:-1}); 2. query all indexes in the current clustered set. userinfo. getindexes (); 3. view the total index record size dB. userinfo. totalindexsize (); 4. Read all index information dB of the current set. users. reindex (); 5. Delete the specified index database. users. dropindex ("name_1"); 6. Delete All index databases. users. dropindexes (); Modify, add, and delete Set Data 1. Add a database. users. save ({Name: 'hangsan ', age: 25, ***: true}); the added data column is not fixed, based on the added data. 2. Modify the database. 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 + 50 where name = 'lisi'; dB. users. update ({Name: 'lisi'}, {$ Inc: {Age: 50}, $ set: {Name: 'ho Ho '}, false, true); equivalent to: Update users set age = age + 50, name = 'hohoo' where name = 'lisi'; 3. delete a database. users. remove ({age: 132}); 4. query, modify, and delete a database. users. findandmodify ({query: {age: {$ GTE: 25 }}, sort: {age:-1}, 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 is a required parameter; other parameters are optional. Parameter description default value query filtering condition {} sort if multiple documents meet the query filtering condition, the first object is selected in the order specified by this parameter, this object will be operated {} remove if it is true, and the selected object will be deleted before return N/aupdate a modifier object N/anew if it is true, the modified object instead of the original object will be returned. This parameter is ignored during the delete operation. For more information about falsefields, see retrieving a subset of fields (1.5.0 +) All fieldsupsert. If the query result is blank, create a new object. Example (1.5.4 +) False statement block Operation 1. Simple Hello worldprint ("Hello world! "); This method calls the print function, and directly writes" Hello world! "The results are the same. 2. convert an object to jsontojson (new object (); tojson (new object ('A ')); 3. Add data cyclically> for (VAR I = 0; I <30; I ++ ){... DB. users. save ({name: "U _" + I, age: 22 + I, ***: I % 2 });...}; in this way, 30 pieces of data are added cyclically, and the brackets can also be omitted> for (VAR I = 0; I <30; I ++) dB. users. save ({name: "U _" + I, age: 22 + I, ***: I % 2. users. you can use it to view information on the next page when multiple data entries are displayed in the find () query but one page is not displayed. 4. Find cursor query> var cursor = dB. users. find ();> while (cursor. hasnext () {printjson (cursor. next ();} in this way, all users information is queried. You can also write var cursor = dB. users. find (); While (cursor. hasnext () {printjson (cursor. next);} can also omit {} 5, foreach iteration cycle dB. users. find (). foreach (printjson); foreach must pass a function to process the data information of each iteration. 6. process the find cursor as an array. var cursor = dB. users. find (); cursor [4]; since the data with the subscript index 4 can be processed as an array, the length of the data can be obtained: cursor. length (); or cursor. count (); then 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 the find cursor to an array> var arr = dB. users. find (). toarray ();> printjson (ARR [2]); use the toarray method to convert it to an array 8. customize our own query results to show only the age <= 28 and only the age column data dB. users. find ({age: {$ LTE: 28 }}, {age: 1 }). foreach (printjson); dB. users. find ({age: {$ LTE: 28 }}, {age: true }). foreach (printjson); Exclude the column dB of age. users. find ({age: {$ LTE: 28 }}, {age: false }). foreach (printjson); 9. The foreach Transfer Function displays the information dB. things. find ({X: 4 }). foreach (function (x) {print (tojson (x ));});
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.