MongoDB Common methods of operation

Source: Internet
Author: User
Tags create index tojson

After the successful start of MongoDB, and then open a command line window input MONGO, you can do some of the database operations. Enter help to see the basic Operations Command, but MongoDB does not have a command to create a database, but there are similar commands

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".
One, Database Common command 1, help view command prompt

Copy CodeThe code is as follows: Help Db.help (); Db.yourColl.help (); Db.youColl.find (). Help (); Rs.help (); 2, switch/CREATE DatabaseCopy CodeThe code is as follows: Use YOURDB; When a collection (table) is created, the current database 3 is automatically created, querying all databasesCopy CodeThe code is as follows: Show Dbs;4, delete the currently used databaseCopy CodeThe code is as follows: Db.dropdatabase (); 5. Cloning a database from a specified hostCopy CodeThe code is as follows: Db.clonedatabase ("127.0.0.1"); Clones data from the database on the specified machine to the current database 6, copying the specified database data from the specified machine to a databaseCopy CodeThe code is as follows: Db.copydatabase ("MyDB", "temp", "127.0.0.1"), copying the native mydb data to the TEMP database 7, repairing the current databaseCopy CodeThe code is as follows: Db.repairdatabase (); 8. View the database currently in useCopy CodeThe code is as follows: Db.getname (); db The DB and GetName methods are the same effect, you can query the currently used database 9, display the current DB statusCopy CodeThe code is as follows: Db.stats (); 10, current DB versionCopy CodeThe code is as follows: Db.version (); 11. View the link machine address of the current DBCopy CodeThe code is as follows: Db.getmongo ();

Collection Aggregation collection 1, create a clustered collection (table)

Copy CodeThe code is as follows: Db.createcollection ("Collname", {size:20, Capped:5, max:100});//Successful creation will show {"OK": 1}// Determines whether the set is a fixed capacity db.collName.isCapped (); 2, gets the specified name of the Aggregation collection (table)Copy CodeThe code is as follows: Db.getcollection ("Account"), 3, gets all the aggregation sets of the current DBCopy CodeThe code is as follows: Db.getcollectionnames (); 4, displays the status of all clustered indexes in the current DBCopy CodeThe code is as follows: Db.printcollectionstats (); third, user-related
1. Add a userCopy CodeThe code is as follows: Db.adduser ("name"); Db.adduser ("UserName", "pwd123", true); Add users, set passwords, read-only 2, database authentication, security modeCopy CodeThe code is as follows: Db.auth ("UserName", "123123"); 3. Show All current usersCopy CodeThe code is as follows: Show users;4, delete userCopy CodeThe code is as follows: Db.removeuser ("UserName"); Iv. Aggregation Collection Query
1. Check all recordsCopy CodeThe code is as follows: Db.userInfo.find (); Equivalent: select* from UserInfo; The default is 20 records per page, and you can query the next page of data with it iteration commands 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 for a column in the current clustered collection after the query is removedCopy CodeThe code is as follows: Db.userInfo.distinct ("name"); Will filter out the same data in name equivalent to: Select Distict name from userinfo;3, query age = 22 recordCopy CodeThe code is as follows: Db.userInfo.find ({"Age": 22}); Equivalent to: SELECT * from userInfo where age = 22;4, query age > 22 RecordsCopy CodeThe code is as follows: Db.userInfo.find ({age: {$gt: 22}}); Equivalent to: SELECT * from UserInfo where age >22;5, query age < 22 recordsCopy CodeThe code is as follows: Db.userInfo.find ({age: {$lt: 22}}); Equivalent to: SELECT * from UserInfo where age <22;6, query age >= 25 RecordsCopy CodeThe code is as follows: Db.userInfo.find ({age: {$gte: 25}}); Equivalent to: SELECT * from UserInfo where age >= 25;7, query age <= 25 RecordsCopy CodeThe code is as follows: Db.userInfo.find ({age: {$lte: 25}}), 8, query age >= 23 and age <= 26Copy CodeThe code is as follows: Db.userInfo.find ({age: {$gte: 9, $lte: 26}}), and query name containing MONGO dataCopy CodeThe code is as follows: Db.userInfo.find ({name:/mongo/}); Equivalent to percent percent [code]select * from UserInfo where name like '%mongo% '; 10, query name in the beginning of the MONGOCopy CodeThe code is as follows: Db.userInfo.find ({name:/^mongo/}); SELECT * from UserInfo where name is like ' mongo% '; 11, query the specified column name, age dataCopy CodeThe code is as follows: Db.userInfo.find ({}, {name:1, age:1}); Equivalent to: Select Name, age from UserInfo, and of course name can also use 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 > 25Copy CodeThe code is as follows: Db.userInfo.find ({age: {$gt: +}}, {name:1, age:1}); Equivalent to: Select Name, age from UserInfo where >25;13, chronologicalCopy CodeThe code is as follows: Ascending: Db.userInfo.find (). Sort ({age:1}); Descending: Db.userInfo.find (). Sort ({Age:-1}); 14, Query name = Zhangsan, age = 22 dataCopy CodeThe code is as follows: Db.userInfo.find ({name: ' Zhangsan ', age:22}); Equivalent to: SELECT * from userInfo where name = ' Zhangsan ' and "age = ' 22 '; 15, query Top 5 dataCopy CodeThe code is as follows: Db.userInfo.find (). Limit (5); Equivalent: selecttop 5 * from userinfo;16, query 10 after the dataCopy CodeThe code is as follows: Db.userInfo.find (). Skip (10); Equivalent to: SELECT * from UserInfo where ID not in (selecttop * from UserInfo), 17, query data between 5-10Copy CodeThe code is as follows: Db.userInfo.find (). Limit (5), can be used for pagination, limit is Pagesize,skip is the first few pages *pagesize 18, OR and the queryCopy CodeThe code is as follows: Db.userInfo.find ({$or: [{age:22}, {age:25}]}); Equivalent to: SELECT * from userInfo where age = $ or age = 25;19, query First DataCopy CodeThe code is as follows: Db.userInfo.findOne (); Equivalent: Selecttop 1 * from UserInfo; Db.userInfo.find (). limit (1); 20. Query the number of record bars for a result setCopy CodeThe code is as follows: Db.userInfo.find ({age: {$gte: +}}). Count (); Equivalent to: SELECT COUNT (*) from UserInfo where age >= 20;21, sort by a columnCopy CodeThe code is as follows: Db.userInfo.find ({sex: {$exists: true}}). Count (); Equivalent to: SELECT COUNT (Sex) from UserInfo; v. Index 1, CREATE indexCopy CodeThe code is as follows: Db.userInfo.ensureIndex ({name:1}); Db.userInfo.ensureIndex ({name:1, TS:-1}); 2, querying all indexes of the current clustered collectionCopy CodeThe code is as follows: Db.userInfo.getIndexes (); 3, view total index record sizeCopy CodeThe code is as follows: Db.userInfo.totalIndexSize (); 4. Read all index information for the current collectionCopy CodeThe code is as follows: Db.users.reIndex (); 5, delete the specified indexCopy CodeThe code is as follows: Db.users.dropIndex ("Name_1"); 6. Delete all index indexesCopy CodeThe code is as follows: Db.users.dropIndexes (); Vi. Modify, add, delete collection data 1, addCopy CodeThe code is as follows: Db.users.save ({name: ' Zhangsan ', age:25, sex:true}), data column of the added data, not fixed, according to the data added 2, modifyCopy CodeThe code is as follows: 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: Update users set age = Age +, name = ' HoHo ' WHERE name = ' Lisi '; 3, deleteCopy CodeThe code is as follows: Db.users.remove ({age:132}); 4, Query modification DeleteCopy CodeThe code is as follows: 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}); Either update or remove is a required parameter; Additional parameters are optional. Parameter details default value
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 {} If True, the selected object will be deleted before returning N/a up Date a 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 seven, statement block operation 1, simple Hello WorldCopy CodeThe code is as follows: Print ("Hello world!"); This notation calls the print function, and writes "Hello world!" directly The effect is the same; 2. Convert an object to JSONCopy CodeThe code is as follows: Tojson (new Object ()); Tojson (New Object (' a ')); 3. Loop to add dataCopy CodeThe code is as follows:> 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 you can also omit the notationCopy CodeThe code is as follows:> for (var i = 0; i <; i++) Db.users.save ({name: "u_" + I, age:22 + i, sex:i% 2}); Yes, when you use Db.users.find ( When you query, you can view the information on the next page by displaying multiple data instead of one page; 4. Find cursor QueryCopy CodeThe code is as follows: >var cursor = Db.users.find (); > while (Cursor.hasnext ()) {Printjson (Cursor.next ());
This can be done by querying all of the users ' information.Copy CodeThe code is as follows: var cursor = Db.users.find (); while (Cursor.hasnext ()) {Printjson (cursor.next);} You can also omit {} # 5, foreach Iteration loopsCopy CodeThe code is as follows: Db.users.find (). foreach (Printjson), a function must be passed in foreach to handle data information for each iteration 6, the Find cursor is treated as an arrayCopy CodeThe code is as follows: var cursor = Db.users.find (); CURSOR[4]; To get the index of subscript 4 that data can be treated as an array, then you can get its length: cursor.length (); or cursor.count (); So we can also display the data in a loopCopy CodeThe code is as follows: for (var i = 0, Len = c.length (), i < Len; i++) Printjson (C[i]); 7, convert find cursor to arrayCopy CodeThe code is as follows:> 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 age <= 28 and only the Age column dataCopy CodeThe code is as follows: Db.users.find ({age: {$lte: +}}, {age:1}). ForEach (Printjson); Db.users.find ({age: {$lte: +}}, {age:true}). ForEach (Printjson); Exclude Age ColumnsCopy CodeThe code is as follows: Db.users.find ({age: {$lte: +}}, {Age:false}). foreach (Printjson); 9, the foreach transfer function displays informationCopy CodeThe code is as follows: Db.things.find ({x:4}). ForEach (function (x) {print (Tojson (x));});

Viii. other 1. Error message before query

Copy CodeThe code is as follows: Db.getpreverror (); 2, clear the Error recordCopy CodeThe code is as follows: 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 ();

MongoDB Common methods of 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.