MongoDB Basic Usage

Source: Internet
Author: User
Tags create index tojson

MongoDB Database Basic usage show DBS: Display Database list  show collections: Displays a collection in the current database (similar to a table in a relational database)  show users: Displays user use : Toggles the current database, It's the same as Ms-sql inside.  db.help (): Displays the database Operations command, which has a lot of commands  db.foo.help (): Displays the set Operation command, also has a lot of commands, Foo refers to the current database, a set called Foo, Not a real 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 The condition is that there is a property in the data called a, 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 commands  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, queries all databases  show dbs;4, deletes the currently used database  db.dropdatabase (), 5, clones 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, 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 be queried for the currentDatabase 9, display the current DB status  db.stats (), 10, current DB version  db.version (), 11, view the current DB link machine address  db.getmongo ();  Collection Aggregation Collection1. Create a Clustered collection (table) db.createcollection ("Collname", {size:20, Capped:5, max:100}), 2, get the clustered collection with the specified name (table) Db.getcollection ("Account"), 3, gets all the aggregation sets of the current DB Db.getcollectionnames (), 4, displays the status of all clustered indexes of the current DB Db.printcollectionstats ();User-related1, 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");other1, the error message before the query Db.getpreverror (); 2, clear the Error Record db.reseterror ();View Aggregate collection basic information 1. Check the 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 db of the current aggregation collection Db.userInfo.getDB (); 5, get the state of the current aggregation db.userInfo.stats (); 6, get the aggregate aggregate size db.userInfo.totalSize (); 7, the aggregate storage space size Db.userInfo.storageSize (); 8, shard version Information Db.userInfo.getShardVersion () 9, Clustered set rename Db.userInfo.renameCollection ("Users "); Rename the UserInfo to Users10, delete the current clustered collection Db.userInfo.drop ();Clustered 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, so that each page shows 50 records.  2 the duplicate data db.userInfo.distinct ("name") of a column in the current clustered collection after the query is removed, and the same data in name is filtered out to the equivalent of: 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 Records db.u Serinfo.find ({age: {$gt: 22}}), equivalent to: SELECT * from UserInfo the Where age >22; 5, query age < 22 record Db.userInfo.find ({age : {$lt: 22}), equivalent to: SELECT * from UserInfo where age <22; 6, query age >= 25 record Db.userInfo.find ({age: {$gte: 25}}); : SELECT * from UserInfo where age >= 25; 7, query age <= 25 record Db.userInfo.find ({age: {$lte: +}});  8, Query Age > = 23 and Age <= 26db.userinfo.find ({age: {$gte:, $lte: +}})  9, query name contains MONGO data Db.userInfo.find ({name:/mong o/});//equivalent to%%select * from UserInfo where name is like '%mongo% ';  10, query name MONGO that begins with Db.userInfo.find ({name:/^mongo/}); select * from userInfo where name like ' mongo% ';  11, query specified column name, age data Db.userInfo.find ({}, {name:1, age:1}); equivalent to: s Elect 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 > 25db.userinfo.find ({age: {$gt: +}}, {name:1, age:1}), equivalent to: select Name, age from Useri NFO where age >25; 13, sort Ascending in chronological order: 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 = ' Zhangsan ' and age = ' n ';  15, query the first 5 data db.userInfo.find (). Limit (5); equivalent: selecttop 5 * from Userinfo; 16, Query data after 10 Db.userInfo.find (). Skip (10), equivalent to: SELECT * from UserInfo where ID not in (selecttop * from UserInfo);  17, check The Data Db.userInfo.find (). Limit (5) can be used for paging, limit is the number of pages *pagesize 18, OR and Query Db.userInfo.find ({$or: [{age:22}, {age:25}]}), equivalent to: SELECT * from UserInfo where age = or age = 25; 19, querying the First Data Db.userInfo.findOne (); equivalent to: Selecttop 1 * from Userinfo;db.userinfo.find (). limit (1); nbsp;20, query the number of record bars for a result set Db.userInfo.find ({age: {$gte: +}}). count (); equal to: Select COUNT (*) from UserInfo where age >= 20;& Nbsp;21, sort by a column db.userInfo.find ({* *: {$exists: true}}). count (); equal to: SELECT COUNT (* * *) from userinfo; Index1. 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, and delete collection data 1, add Db.users.save ({name: ' Zhangsan ', age:25, * * *: true}), the data column of the added data, is not 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.user S.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 +, NA me = ' HoHo ' WHERE name = ' Lisi ';  3, delete db.users.remove ({age:132});  4, query Modify Delete db.users.findAndModify ({    Query: {age: {$gte:25}},     sort: {age: -1},     Update: {$set: {name: ' A2 '}, $inc: {age:2}},    Remove:true});  db.runcommand ({findandmodify: "users",     query: {age: {$g te:25}},     Sort: {age: -1},     Update: {$set: {name: ' A2 '}, $inc: {age:2}},  &nbsp ; Remove:true}); Update or remove one of them isthe required parameters; 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, converts an object to Jsontojson (new Object ()), Tojson (New object (' a ')),  3, loops 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 (), displaying multiple data and not displaying it on one page;  4, find cursor query >var cursor = Db.users.find ();> while (Cursor.hasnext ()) {     Printjson (Cursor.next ()), &nbsp, and so on all users information, the same can be said var cursor = Db.users.find (); while (Cursor.hasnext ()) {Printjson (cursor.next);} You can also omit the {} number  5, the foreach Iteration Loop Db.users.find (). foreach (Printjson), and 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 with the subscript index 4 can be processed as an array, so it can be obtained in length: Cursor.length (); or Cursor.count (); So we can also display the data for (var i = 0, Len = c.length (), I < Len, i++) Printjson (C[i]) in the loop, and  7, the find cursor conversions to arrays > var arr = db.users.find (). ToArray ();> Printjson (arr[2]); convert it to an array toArray using the  8 method, customize 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));});   reproduced in this article from http://blog.chinaunix.net/uid-26558059-id-3211264.html

MongoDB Basic Usage

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.