MongoDB Common operation Commands Daquan _mongodb

Source: Internet
Author: User
Tags create index mongodb tojson create database

For example, if you want to create a "myTest" database, run the use MyTest command, and then do something (such as db.createcollection (' user '), so you can create a database called "myTest."

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

Copy Code code as follows:
Help
Db.help ();
Db.yourColl.help ();
Db.youColl.find (). Help ();
Rs.help ();

2. Switch/CREATE Database
Copy Code code as follows:
Use Yourdb; The current database is created automatically when a collection (table) is created

3, query all databases
Copy Code code as follows:
Show DBS;

4, delete the current use of the database
Copy Code code as follows:
Db.dropdatabase ();

5, clone the database from the designated host
Copy Code code as follows:
Db.clonedatabase ("127.0.0.1"); Clones data from the database on the specified machine to the current database

6. Copy the specified database data to a database from the specified machine
Copy Code code as follows:
Db.copydatabase ("MyDB", "temp", "127.0.0.1"); Copy native mydb data to the TEMP database

7, repair the current database
Copy Code code as follows:
Db.repairdatabase ();

8. View the database currently in use
Copy Code code as follows:
Db.getname ();
db DB and GetName methods are the same effect, you can query the currently used database

9, display the current DB status
Copy Code code as follows:
Db.stats ();

10, the current DB version
Copy Code code as follows:
Db.version ();

11, view the current DB link machine address
Copy Code code as follows:
Db.getmongo ();

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

Copy Code code as follows:
Db.createcollection ("Collname", {size:20, Capped:5, max:100});//Create success will show {"OK": 1}
Determine whether the set is a fixed capacity db.collName.isCapped ();

2, get the specified name of the aggregation set (table)
Copy Code code as follows:
Db.getcollection ("account");

3, get the current db of all the aggregation set
Copy Code code as follows:
Db.getcollectionnames ();

4. Displays the status of all clustered indexes in the current DB
Copy Code code as follows:
Db.printcollectionstats ();

Third, user-related
1. Add a user
Copy Code code as follows:
Db.adduser ("name");
Db.adduser ("UserName", "pwd123", true); Add user, set password, read only

2. Database Authentication and Safe mode
Copy Code code as follows:
Db.auth ("UserName", "123123");

3. Show all current users
Copy Code code as follows:
Show Users;

4, delete the user
Copy Code code as follows:
Db.removeuser ("UserName");

Aggregate collection Query
1. Check all records
Copy Code code as follows:
Db.userInfo.find ();
Equivalent to: select* from UserInfo;

The default display of 20 records per page, when not displayed, you can use it iterative command to query the next page of data. Note: type it command without ";"
But you can set the size of each page to display the data, 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 has been removed
Copy Code code as follows:
Db.userInfo.distinct ("name");
Will filter out the same data in name
Equivalent: Select Distict name from UserInfo;

3, Query age = 22 Records
Copy Code code as follows:
Db.userInfo.find ({"Age": 22});
Equivalent to: SELECT * from userInfo where age = 22;

4. Check the records of age > 22
Copy Code code as follows:
Db.userInfo.find ({age: {$gt: 22}});
Equivalent to: SELECT * from UserInfo where age >22;

5. Check the records of age < 22
Copy Code code as follows:
Db.userInfo.find ({age: {$lt: 22}});
Equivalent to: SELECT * from UserInfo where age <22;

6. Check the records of age >= 25
Copy Code code as follows:
Db.userInfo.find ({age: {$gte: 25}});
Equivalent to: SELECT * from UserInfo where age >= 25;

7. Check the records of age <= 25
Copy Code code as follows:
Db.userInfo.find ({age: {$lte: 25}});

8. Query age >= 23 and age <= 26
Copy Code code as follows:
Db.userInfo.find ({age: {$gte: $lte: 26}});

9, query name contains MONGO data
Copy Code code as follows:
Db.userInfo.find ({name:/mongo/});
Equal to%
[Code]select * from UserInfo where name like '%mongo% ';

10, query name in the beginning of the MONGO
Copy Code code as follows:
Db.userInfo.find ({name:/^mongo/});
SELECT * from UserInfo where name like ' mongo% ';

11. Query Specify column name, age data
Copy Code code as follows:
Db.userInfo.find ({}, {name:1, age:1});
Equivalent to: Select Name, age from UserInfo;

Of course, name can also use True or false, as with ture in the case of river Name:1 effect, if False is excluding name, display column information other than name.
12. Query Specify column name, age data, age > 25
Copy Code code 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
Copy Code code as follows:
Ascending: Db.userInfo.find (). Sort ({age:1});
Descending: Db.userInfo.find (). Sort ({Age:-1});

14, Query name = Zhangsan, age = 22 data
Copy Code code 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
Copy Code code as follows:
Db.userInfo.find (). Limit (5);
Equivalent to: Selecttop 5 * from UserInfo;

16, query 10 after the data
Copy Code code as follows:
Db.userInfo.find (). Skip (10);
Equivalent to: SELECT * from UserInfo where ID isn't in (
Selecttop from UserInfo
);

17, the query in the data between 5-10
Copy Code code as follows:
Db.userInfo.find (). Limit (a). Skip (5);

Can be used for pagination, limit is Pagesize,skip is the first few pages *pagesize
18, OR and query
Copy Code code as follows:
Db.userInfo.find ({$or: [{age:22}, {age:25}]});
Equivalent to: SELECT * from userInfo where age = 25;

19, query the first piece of data
Copy Code code as follows:
Db.userInfo.findOne ();
Equivalent to: Selecttop 1 * from UserInfo;
Db.userInfo.find (). limit (1);

20, query a result set of the number of records
Copy Code code as follows:
Db.userInfo.find ({age: {$gte:}}). Count ();
Equivalent to: SELECT COUNT (*) from UserInfo where age >= 20;

21, according to a column to sort
Copy Code code as follows:
Db.userInfo.find ({sex: {$exists: true}}). Count ();
Equivalent to: SELECT COUNT (Sex) from userInfo;

Five, index
1. CREATE index
Copy Code code as follows:
Db.userInfo.ensureIndex ({name:1});
Db.userInfo.ensureIndex ({name:1, TS:-1});

2. Querying all indexes of the current aggregation collection
Copy Code code as follows:
Db.userInfo.getIndexes ();

3. View the total index record size
Copy Code code as follows:
Db.userInfo.totalIndexSize ();

4. Read all index information for the current collection
Copy Code code as follows:
Db.users.reIndex ();

5, delete the specified index
Copy Code code as follows:
Db.users.dropIndex ("Name_1");

6. Delete all index indexes
Copy Code code as follows:
Db.users.dropIndexes ();

Vi. modifying, adding, and deleting collection data
1, add
Copy Code code as follows:
Db.users.save ({name: ' Zhangsan ', age:25, sex:true});

The data column of the added data, not fixed, according to the added data
2, modify
Copy Code code 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: 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
Copy Code code as follows:
Db.users.remove ({age:132});

4, query Modify Delete
Copy Code code 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 the necessary parameters; Other parameters are optional.
Parameter detailed default value
Query filter Criteria {}
Sort if more than one document conforms to the query filtering criteria, the first-ranked object will be selected in the arrangement specified by the parameter, and the object will be manipulated {}
If remove is true, the selected object will be deleted before it returns N/A
Update a Modifier object
N/A
If new is true, the modified object is returned instead of the original object.    In a delete operation, this 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
VII. Statement block operations
1, simple Hello World
Copy Code code as follows:
Print ("Hello world!");

This type of writing invokes the print function, and writes directly to "Hello world!" The effect is the same;
2. Convert an object to JSON
Copy Code code as follows:
Tojson (New Object ());
Tojson (New Object (' a '));

3. Recycle Add Data
Copy Code code as follows:
> for (var i = 0; i < i++) {
... db.users.save ({name: "u_" + I, age:22 + i, sex:i% 2});
... };

This allows you to add 30 of data to the loop, but also omit the notation of parentheses.
Copy Code code 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 Db.users.find () query, display more than one page of data, you can use it to view the next page of information;
4, Find cursor query
Copy Code code 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 write
Copy Code code as follows:
var cursor = Db.users.find ();
while (Cursor.hasnext ()) {Printjson (cursor.next);}

You can also omit the {} number
5. Foreach Iterative cycle
Copy Code code as follows:
Db.users.find (). ForEach (Printjson);

foreach must pass a function to handle the data information for each iteration
6, the Find cursor when the array processing
Copy Code code as follows:
var cursor = Db.users.find ();
CURSOR[4];

Get the data for the subscript index of 4
Since it can be treated as an array, it can be obtained in length: Cursor.length () or cursor.count ();
So we can also use the loop to display the data.
Copy Code code as follows:
for (var i = 0, Len = c.length (); i < Len; i++) Printjson (c[i));

7. Convert find cursor to array
Copy Code code as follows:
> var arr = db.users.find (). ToArray ();
> Printjson (arr[2]);

Convert it to an array by using the ToArray method
8. Customize our own query results
Show only age <= 28 and show only age this column of data
Copy Code code as follows:
Db.users.find ({age: {$lte:}}, {age:1}). ForEach (Printjson);
Db.users.find ({age: {$lte:}}, {age:true}). ForEach (Printjson);

Exclude an Age column
Copy Code code as follows:
Db.users.find ({age: {$lte:}}, {Age:false}). ForEach (Printjson);

9, the foreach transfer function display information
Copy Code code as follows:
Db.things.find ({x:4}). ForEach (function (x) {print (Tojson (x));});

Viii. Other
1, the error message before the query

Copy Code code as follows:
Db.getpreverror ();

2. Clear Error Record
Copy Code code as follows:
Db.reseterror ();

To view the basic information of a clustered collection
1, see Help Db.yourColl.help ();
2, query the current set of data bar number Db.yourColl.count ();
3, view the size of the data Space db.userInfo.dataSize ();
4. Get the DB Db.userInfo.getDB () where the current aggregation set is located;
5, get the current aggregation state db.userInfo.stats ();
6, get the aggregate aggregate size db.userInfo.totalSize ();
7, the aggregation set storage space size db.userInfo.storageSize ();
8, shard version information Db.userInfo.getShardVersion ()
9, gather the collection to rename Db.userInfo.renameCollection ("Users"); Rename UserInfo to users
10, delete the current aggregation set Db.userInfo.drop ();

Copy Code code as follows:
Show DBS: Displaying a list of databases
Show Collections: Displays the collection in the current database (similar to tables in a relational database)
Show Users: displaying user
Use <db name>: Toggle the current database, which is the same as in Ms-sql.
Db.help (): Display database operation commands, there are 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 collection called Foo, not the true 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}): Finds a collection of Foo in the current database, provided that one of the properties in the data is called a, and A has a value of 1

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.