MongoDB Common Operations Command Daquan

Source: Internet
Author: User
Tags 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". There is a table named "User" under the library.

First, the database commonly used commands
1. Help View command Prompt

The code is as follows:

Help
Db.help ();
Db.yourColl.help ();
Db.youColl.find (). Help ();
Rs.help ();


2. Switch/CREATE Database

The code is as follows:

Use Yourdb; The current database is created automatically when a collection (table) is created


3. Query all databases

The code is as follows:

Show DBS;


4. Delete the currently used database

The code is as follows:

Db.dropdatabase ();


5. Cloning a database from a specified host

The code is as follows:

Db.clonedatabase ("127.0.0.1"); Clones data from a database on a specified machine to the current database


6. Copy the specified database data from the specified machine to a database

The code is as follows:

Db.copydatabase ("MyDB", "temp", "127.0.0.1"), copy the native mydb data to the TEMP database


7. Repairing the current database

The code is as follows:

Db.repairdatabase ();


8. View the database currently in use

The code is as follows:

Db.getname ();
db The DB and GetName methods are the same effect and can query the currently used database


9. Display the current DB status

The code is as follows:

Db.stats ();


10. Current DB version

The code is as follows:

Db.version ();


11. View the current DB link machine address

The code is as follows:

Db.getmongo ();

Second, collection aggregation set
1. Create a Clustered collection (table)

The code is as follows:

Db.createcollection ("Collname", {size:20, Capped:5, max:100});//Successful creation will show {"OK": 1}
Determine whether the set is a fixed capacity db.collName.isCapped ();


2. Get a clustered collection with the specified name (table)

The code is as follows:

Db.getcollection ("account");


3. Get all the aggregation sets of the current DB

The code is as follows:

Db.getcollectionnames ();


4. Displays the status of all clustered indexes in the current DB

The code is as follows:

Db.printcollectionstats ();


Third, user-related
1. Add a user

The code is as follows:

Db.adduser ("name");
Db.adduser ("UserName", "pwd123", true); Add user, set password, read-only


2, database authentication, security mode

The code is as follows:

Db.auth ("UserName", "123123");


3. Show all current users

The code is as follows:

Show Users;


4. Delete users

The code is as follows:

Db.removeuser ("UserName");


Iv. Aggregation Collection Query
1. Check all records

The 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 the IT iteration command when the display is not displayed. Note: Type the IT command cannot take ";"
However, you can set the size of the data displayed on each page, using dbquery.shellbatchsize= 50, which shows 50 records per page.
2. Duplicate data for a column in the current clustered collection after the query is removed

The code is as follows:

Db.userInfo.distinct ("name");
Will filter out the same data in name
Equivalent: Select Distict name from UserInfo;


3. Check the record of age = 22

The code is as follows:

Db.userInfo.find ({"Age": 22});
Equivalent to: SELECT * from userInfo where age = 22;


4. Check the records of age > 22

The code is as follows:

Db.userInfo.find ({age: {$gt: 22}});
Equivalent to: SELECT * from UserInfo where >22;


5. Check the records of age < 22

The code is as follows:

Db.userInfo.find ({age: {$lt: 22}});
Equivalent to: SELECT * from UserInfo where <22;


6. Check the records of age >= 25

The code is as follows:

Db.userInfo.find ({age: {$gte: 25}});
Equivalent to: SELECT * from UserInfo where age >= 25;


7. Check the records of age <= 25

The code is as follows:

Db.userInfo.find ({age: {$lte: 25}});


8. Query age >= 23 and age <= 26

The code is as follows:

Db.userInfo.find ({age: {$gte: $lte: 26}});


9. Query the data containing MONGO in name

The code is as follows:

Db.userInfo.find ({name:/mongo/});
Equal to percent
[Code]select * from UserInfo where name like '%mongo% ';


10, query the name in the beginning of MONGO

The code is as follows:

Db.userInfo.find ({name:/^mongo/});
SELECT * from UserInfo where name is like ' mongo% ';


11. Query the specified column name, age data

The code is as follows:

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 > 25

The code is as follows:

Db.userInfo.find ({age: {$gt: +}}, {name:1, age:1});
Equivalent to: Select Name, age from UserInfo where age >25;


13. Sort by age

The code is as follows:

Ascending: Db.userInfo.find (). Sort ({age:1});
Descending: Db.userInfo.find (). Sort ({Age:-1});


14. Query name = Zhangsan, age = 22 data

The code is as follows:

Db.userInfo.find ({name: ' Zhangsan ', age:22});
Equivalent to: SELECT * from userInfo where name = ' Zhangsan ' and "age = ' 22 ';


15, query the first 5 data

The code is as follows:

Db.userInfo.find (). Limit (5);
Equivalent: selecttop 5 * from UserInfo;


16, query 10 after the data

The code is as follows:

Db.userInfo.find (). Skip (10);
Equivalent to: SELECT * from UserInfo where ID not in (
Selecttop * from UserInfo
);


17, query the data between 5-10

The code is as follows:

Db.userInfo.find (). Limit (Ten). Skip (5);


Can be used for pagination, limit is Pagesize,skip is the first few pages *pagesize
18, OR and query

The code is as follows:

Db.userInfo.find ({$or: [{age:22}, {age:25}]});
Equivalent to: SELECT * from UserInfo where is age = 25


19. Query the first piece of data

The 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 set

The code is as follows:

Db.userInfo.find ({age: {$gte: +}}). Count ();
Equivalent to: SELECT COUNT (*) from UserInfo where age >= 20;


21. Sort by a column

The code is as follows:

Db.userInfo.find ({sex: {$exists: true}}). Count ();
Equivalent to: SELECT COUNT (Sex) from userInfo;


Five, index
1. Create an index

The code is as follows:

Db.userInfo.ensureIndex ({name:1});
Db.userInfo.ensureIndex ({name:1, TS:-1});


2. Querying all indexes of the current aggregation collection

The code is as follows:

Db.userInfo.getIndexes ();


3. View Total index record size

The code is as follows:

Db.userInfo.totalIndexSize ();


4. Read all index information for the current collection

The code is as follows:

Db.users.reIndex ();


5. Delete the specified index

The code is as follows:

Db.users.dropIndex ("Name_1");


6. Delete all index indexes

The code is as follows:

Db.users.dropIndexes ();


Vi. Modify, add, and delete collection data
1. Add

The 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. Modification

The 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 to: Update users set age = Age +, name = ' HoHo ' WHERE name = ' Lisi ';


3. Delete

The code is as follows:

Db.users.remove ({age:132});


4, Query modification Delete

The code is as follows:

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:  {$gte:  25}}, 
    sort: {age: -1}, 
     update: {$set: {name:  ' A2 '},  $inc:  {age: 2}},
     remove: true
});


Update or remove one of them 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 is manipulated {}
Remove if True, the selected object will be deleted before returning N/a
Update a Modifier object
N/A
If new is 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 World

The 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 JSON

The code is as follows:

Tojson (New Object ());
Tojson (New Object (' a '));


3. Loop Add data

The 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 notation

The code is as follows:

> for (var i = 0; i < i++) Db.users.save ({name: "u_" + I, age:22 + i, sex:i% 2});


is also possible, when you use the 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

The code is as follows:

>var cursor = Db.users.find ();
> while (Cursor.hasnext ()) {
Printjson (Cursor.next ());
}


This allows you to query all the users information, as well as to write

The code is as follows:

var cursor = Db.users.find ();
while (Cursor.hasnext ()) {Printjson (cursor.next);}


You can also omit the {} number
5. Foreach Iteration Loops

The code is as follows:

Db.users.find (). ForEach (Printjson);


A function must be passed in foreach to process data information for each iteration
6. Treat the Find cursor as an array

The code is as follows:

var cursor = Db.users.find ();
CURSOR[4];


Get the data for subscript index 4
Since it can be treated as an array, its length can be obtained: Cursor.length (); or cursor.count ();
So we can also display the data in a loop

The code is as follows:

for (var i = 0, Len = c.length (); i < Len; i++) Printjson (C[i]);


7. Convert the Find cursor to an array

The code is as follows:

> var arr = db.users.find (). ToArray ();
> Printjson (arr[2]);


To convert it to an array using the ToArray method
8. Customize our own query results
Only age <= 28 is displayed and only the Age column data is displayed

The code is as follows:

Db.users.find ({age: {$lte: +}}, {age:1}). ForEach (Printjson);
Db.users.find ({age: {$lte: +}}, {age:true}). ForEach (Printjson);


Exclude The Age column

The code is as follows:

Db.users.find ({age: {$lte: +}}, {Age:false}). ForEach (Printjson);


9. The Foreach transfer function displays information

The code is as follows:

Db.things.find ({x:4}). ForEach (function (x) {print (Tojson (x));});

Viii. Other
1, the error message before the query

The code is as follows:

Db.getpreverror ();


2. Clear the Error Record

The code is as follows:

Db.reseterror ();


View Aggregate Collection basic information
1, check the 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 aggregation set Db.userInfo.drop ();

The code is as follows:

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 the meaning in Ms-sql
Db.help (): Show database Operations Command with a lot of commands
Db.foo.help (): Displays the set Operation command, as well as a lot of commands, Foo refers to the current database, a collection 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}): Looks for the Foo collection in the current database, provided the data has a property called a, and A has a value of 1

MongoDB Common Operations Command Daquan

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.