MongoDB learning-command operations

Source: Internet
Author: User
Tags tojson

[From: http://hi.baidu.com/jadmin/blog/item/c734ab589cc52bc69d82043b.html]

I. DB shell database operations

Database

1. Help to view command prompts
Help
DB. Help ();
DB. yourcoll. Help ();
DB. youcoll. Find (). Help ();
Rs. Help ();

2. Switch to/create a database
> Use yourdb;
When a table is created, the current database is automatically created.

3. query all databases
Show dBs;

4. Delete the currently used database
DB. dropdatabase ();

5. clone a database from a specified host
DB. clonedatabase ("127.0.0.1 ");
Clone the database data on the specified machine to the current database

6. Copy the specified database data from the specified machine to a database
DB. copydatabase ("mydb", "Temp", "127.0.0.1 ");
Copy the mydb data of the local machine 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 have the same effect. You can query the currently used database.

9. display the current dB status
DB. Stats ();

10. Current DB version
DB. Version ();

11. view the address of the linked machine of the current DB

DB. getmongo ();

Collection aggregation set

1. Create an aggregation set (table)
DB. createcollection ("collname", {size: 20, capped: 5, Max: 100 });

2. Get the clustering set (table) with the specified name)
DB. getcollection ("account ");

3. obtain all the aggregation sets of the current dB.
DB. getcollectionnames ();

4. display the status of all clustered indexes of the current DB
DB. printcollectionstats ();

User-related

1. Add a user
DB. adduser ("name ");
DB. adduser ("username", "pwd123", true );
Add a user, set a password, and check whether the user is read-only

2. database authentication and security mode
DB. Auth ("username", "123123 ");

3. display all current users
Show users;

4. delete a user
DB. removeuser ("username ");

Others

1. query previous error messages
DB. getpreverror ();

2. Clear error records
DB. reseterror ();

2. Collection collection operation

View basic information about a collection

1. View help
DB. yourcoll. Help ();

2. query the number of data entries in the current set
DB. yourcoll. Count ();

3. view the data space size
DB. userinfo. datasize ();

4. Obtain the dB of the current collection.
DB. userinfo. getdb ();

5. Get the current cluster status
DB. userinfo. Stats ();

6. Get the total size of the aggregation 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 clustering set
DB. userinfo. renamecollection ("users ");
Rename userinfo to users

10. Delete the current collection.
DB. userinfo. Drop ();

Aggregate collection Query
1. query all records
DB. userinfo. Find ();
Equivalent to: Select * From userinfo;
By default, 20 records are displayed on each page. If no record is displayed, you can use the IT iteration command to query data on the next page. Note: The it command cannot contain ";"
However, you can set the size of data displayed on each page. Use dbquery. shellbatchsize = 50 to display 50 records on each page.

2. query duplicate data of a column in the current clustering set after Removal
DB. userinfo. Distinct ("name ");
The same data in name is filtered out.
Equivalent to: Select distict name from userinfo;

3. query records with age = 22
DB. userinfo. Find ({"Age": 22 });
Equivalent to: Select * From userinfo where age = 22;

4. query records of age> 22
DB. userinfo. Find ({age: {$ GT: 22 }});
Equivalent to: Select * From userinfo where age> 22;

5. query records of age <22
DB. userinfo. Find ({age: {$ LT: 22 }});
Equivalent to: Select * From userinfo where age <22;

6. query records with age> = 25
DB. userinfo. Find ({age: {$ GTE: 25 }});
Equivalent to: Select * From userinfo where age> = 25;

7. query records of age <= 25
DB. userinfo. Find ({age: {$ LTE: 25 }});

8. query age> = 23 and age <= 26
DB. userinfo. Find ({age: {$ GTE: 23, $ LTE: 26 }});

9. query data whose name contains Mongo
DB. userinfo. Find ({Name:/Mongo /});
// Equivalent to %
Select * From userinfo where name like '% Mongo % ';

10. query names starting with Mongo
DB. userinfo. Find ({Name:/^ Mongo /});
Select * From userinfo where name like 'mongo % ';

11. query the name and age data of a specified Column
DB. userinfo. Find ({}, {Name: 1, age: 1 });
Equivalent to: Select name, age from userinfo;
Of course, "true" or "false" can be used for name. If "true" is used, "river name: 1" has the same effect. If "false" is used, "name" is excluded and column information other than "name" is displayed.

12. query the name and age data of a specified column. age> 25
DB. userinfo. Find ({age: {$ GT: 25 },{ name: 1, age: 1 });
Equivalent to: Select name, age from userinfo where age> 25;

13. sort by age
Ascending Order: DB. userinfo. Find (). Sort ({age: 1 });
Descending order: DB. userinfo. Find (). Sort ({age:-1 });

14. query data with name = zhangsan and age = 22
DB. userinfo. Find ({Name: 'hangsan', age: 22 });
Equivalent to: Select * From userinfo where name = 'hangsan' and age = '22 ';

15. query the first five data entries
DB. userinfo. Find (). Limit (5 );
Equivalent to: Select top 5 * From userinfo;

16. Query 10 data records later
DB. userinfo. Find (). Skip (10 );
Equivalent to: Select * From userinfo where id not in (
Select top 10 * From userinfo
);

17. query data between 5-10
DB. userinfo. Find (). Limit (10). Skip (5 );
It can be used for paging. limit is pagesize, and 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 entry.
DB. userinfo. findone ();
Equivalent to: Select top 1 * From userinfo;
DB. userinfo. Find (). limit (1 );

20. query the number of records in a result set
DB. userinfo. Find ({age: {$ GTE: 25}). Count ();
Equivalent to: Select count (*) from userinfo where age> = 20;

21. sort by Column
DB. userinfo. Find ({sex: {$ exists: true}). Count ();
Equivalent to: Select count (sex) from userinfo;

Index

1. Create an index
DB. userinfo. ensureindex ({Name: 1 });
DB. userinfo. ensureindex ({Name: 1, TS:-1 });

2. query all indexes of the current clustered set
DB. userinfo. getindexes ();

3. view the total index record size
DB. userinfo. totalindexsize ();

4. Read all index information of the current set
DB. Users. reindex ();

5. delete a specified index
DB. Users. dropindex ("name_1 ");

6. Delete All indexes
DB. Users. dropindexes ();

Modify, add, and delete Set Data
1. Add
DB. Users. Save ({Name: 'hangsan', age: 25, sex: true });
The data column of the added data is not fixed. The data column is subject to the added data.

2. Modify
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 + 50 where name = 'lisi ';

DB. users. update ({Name: 'lisi'}, {$ Inc: {Age: 50}, $ set: {Name: 'hohoho'}, false, true );
Equivalent to: Update users set age = age + 50, name = 'hohoho' where name = 'lisi ';

3. Delete
DB. Users. Remove ({age: 132 });

4. query, modify, and 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 :{$ 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.

Parameters
Details
Default Value
Query query filtering condition {}
Sort if multiple documents meet the query filtering conditions, the first object will be selected in the order specified by this parameter, and the object will be operated {}
If this parameter is set to true, the selected object will be deleted before return.
Update a modifier object N/
If new is true, the modified object is returned instead of the original object. This parameter is ignored during the delete operation. False
For fields, see retrieving a subset of fields (1.5.0 +) all fields.
If the query result is null, create a new object in upsert. Example (1.5.4 +) False

Statement block Operation
1. Simple Hello World
Print ("Hello world! ");
This method calls the print function and directly writes "Hello world! "The effect is the same;

2. convert an object to JSON
Tojson (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, sex: 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, sex: I % 2 });
You can also use it to view information on the next page when you use dB. Users. Find () to query multiple data entries and cannot display one page;

4. Find cursor Query
> Var cursor = dB. Users. Find ();
> While (cursor. hasnext ()){
Printjson (cursor. Next ());
}
In this way, all users information can be queried.
VaR cursor = dB. Users. Find ();
While (cursor. hasnext () {printjson (cursor. Next );}
You can also omit the {} number.

5. foreach iteration Loop
DB. Users. Find (). foreach (printjson );
In foreach, a function must be passed to process the data information of each iteration.

6. process the find cursor as an array
VaR cursor = dB. Users. Find ();
Cursor [4];
Obtain the data with the subscript index 4.
Since it can be processed as an array, We can get its length: cursor. Length (); or cursor. Count ();
In this way, we can also display data cyclically.
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]);
Convert toarray to an array

8. customize our own query results
Only show age <= 28 and only show age data
DB. Users. Find ({age: {$ LTE: 28 },{ age: 1}). foreach (printjson );
DB. Users. Find ({age: {$ LTE: 28 },{ age: true}). foreach (printjson );
Exclude age Columns
DB. Users. Find ({age: {$ LTE: 28 },{ age: false}). foreach (printjson );

9. foreach transfer function display information
DB. Things. Find ({X: 4}). foreach (function (x) {print (tojson (x ));});
As mentioned above, foreach needs to pass a function. The function will accept a parameter, that is, the object of the current loop, and then process the input parameter information in the function weight.

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.