DB Shell Data operation
Shell command manipulation syntax is similar to JavaScript, in fact, the bottom of the console query statements are done with JavaScript script.
#数据库 operation
1. Help View command Prompt
> help> db.help ();> db.yourColl.help ();> db.youColl.find (). Help ();> rs.help ();
2. Switch/CREATE Database
> Use YOURDB;
The current database is created automatically when a collection (table) is created
3. Query all databases
> Show DBS;
4. Delete the currently used database
> Db.dropdatabase ();
5. Cloning a database from a specified host
> 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
> db.copydatabase ("mydb", "temp", "127.0.0.1");
Copy the MyDB data from the native to the temp database
7. Repairing the current database
> Db.repairdatabase ();
8. View the database currently in use
> Db.getname ();
The DB and GetName methods are the same effect and can query the currently used database
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聚集集合
1. Create a Clustered collection (table)
> db.createcollection ("Collname", {size:20, Capped:5, max:100});
2. Get a clustered collection with the specified name (table)
> db.getcollection ("Account");
3. Get all the aggregation sets of the current DB
> Db.getcollectionnames ();
4. Displays the status of all clustered indexes in the current DB
> Db.printcollectionstats ();
#用户相关
1. Add a user
> Db.adduser ("name"); > Db.adduser ("UserName", "pwd123", true);
Add user, set password, read-only
2, database authentication, security mode
> Db.auth ("UserName", "123123");
3. Show all current users
> Show Users;
4. Delete users
> Db.removeuser ("UserName");
#其他
1, the error message before the query
> Db.getpreverror ();
2. Clear the Error Record
> Db.reseterror ();
Three, collection aggregation set operation
#查看聚集集合基本信息
1. View Help
> Db.yourColl.help ();
2. Query the number of data bars in the current collection
> Db.yourColl.count ();
3. View data space size
4. Get the db where the current aggregation collection resides
5. Get the current aggregation status
> 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. Clustered Collection Rename
> Db.userInfo.renameCollection ("Users");
Rename UserInfo to users
10. Delete the current aggregation collection
> Db.userInfo.drop ();
#聚集集合查询
1. Check all records
> Db.userInfo.find ();
Equivalent to: 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, so that 50 records per page are displayed.
2. Duplicate data for a column in the current clustered collection after the query is removed
> 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
> Db.userInfo.find ({"Age": 22});
Equivalent to: SELECT * from userInfo where age = 22;
4. Check the records of age > 22
> Db.userInfo.find ({age: {$gt: 22}});
Equivalent to: SELECT * from UserInfo where age > 22;
5. Check the records of age < 22
> Db.userInfo.find ({age: {$lt: 22}});
Equivalent to: SELECT * from UserInfo where age < 22;
6. Check the records of age >= 25
> Db.userInfo.find ({age: {$gte: 25}});
Equivalent to: SELECT * from UserInfo where age >= 25;
7. Check the records of age <= 25
> Db.userInfo.find ({age: {$lte: 25}});
8. Query age >= 23 and age <= 26
> Db.userInfo.find ({age: {$gte: $lte: 26}});
9. Query the data containing MONGO in name
> Db.userInfo.find ({name:/mongo/});
Equivalent to: SELECT * from UserInfo where name like '%mongo% ';
10, query the name in the beginning of MONGO
> Db.userInfo.find ({name:/^mongo/});
SELECT * from UserInfo where name is like ' mongo% ';
11. Query the specified column name, age data
> 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
> Db.userInfo.find ({age: {$gt: +}}, {name:1, age:1});
Equivalent to: Select Name, age from UserInfo where age > 25;
13. Sort by age
Ascending:
> 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 to: SELECT * from userInfo where name = ' Zhangsan ' and "age = ' 22 ';
15, query the first 5 data
> Db.userInfo.find (). Limit (5);
Equivalent: SELECT Top 5 * from UserInfo;
16, query 10 after the data
> Db.userInfo.find (). Skip (10);
Equivalent to: SELECT * from UserInfo where ID not in (select Top ten * from UserInfo);
17, query the data between 5-10
> 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
> Db.userInfo.find ({$or: [{age:22}, {age:25}]});
Equivalent to: SELECT * from UserInfo where is age = 25
19. Query the first piece of data
> Db.userInfo.findOne ();
Equivalent: SELECT top 1 * from UserInfo;
> Db.userInfo.find (). limit (1);
20. Query the number of record bars for a result set
> Db.userInfo.find ({age: {$gte: +}}). Count ();
Equivalent to: SELECT COUNT (*) from UserInfo where age >= 20;
21. Sort by a column
> db.userInfo.find ({sex: {$exists: true}}). Count ();
Equivalent to: SELECT COUNT (Sex) from userInfo;
#索引
1. Create an index
> Db.userInfo.ensureIndex ({name:1});> Db.userInfo.ensureIndex ({name:1, TS:-1});
2. Querying all indexes of the current aggregation collection
> db.userInfo.getIndexes ();
3. View Total index record size
> db.userInfo.totalIndexSize ();
4. Read all index information for the current collection
> Db.users.reIndex ();
5. Delete the specified index
> Db.users.dropIndex ("Name_1");
6. Delete all index indexes
> db.users.dropIndexes ();
#修改, add, and delete collection data
1. Add
> Db.users.save ({name: ' Zhangsan ', age:25, sex:true});
Data column of the added data, not fixed, according to the data added
2. Modification
> 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
> Db.users.remove ({age:132});
4, Query modification Delete
> db.users.findAndModify ({ ... query: {age: {$gte: +}}, ... sort: {Age:-1}, ... update: {$set: {name: ' A2 '}, $inc: {age:2}}, ... remove:true }); > Db.runcommand ({findandmodify: "Users", ...) query: {age: {$gte: +}}, ... sort: {Age:-1}, ... update: { $set: {name: ' A2 '}, $inc: {age:2}}, ... remove:true ... });
Update or remove one is a required parameter, and other parameters are optional.
Parameters |
Detailed |
Default value |
Query |
Query Filter Criteria |
{} |
Sort |
If multiple documents conform to a query filter, the first-ranked object will be 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/A |
Update |
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 |
Creates a new object if the query result is empty. Example (1.5.4+) |
False |
1. Simple Hello World
> 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
> Tojson (New Object ()); > Tojson (New Object (' a '));
3. Loop Add data
> 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
> 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
>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
>var cursor = Db.users.find (); >while (Cursor.hasnext ()) {Printjson (cursor.next);}
You can also omit the {} number
5. Foreach Iteration Loops
>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
> 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
> 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]);
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
> Db.users.find ({age: {$lte: +}}, {age:1}). ForEach (Printjson);
Exclude 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));});
As described above, foreach needs to pass a function that takes a parameter, that is, the object that is currently looping, and then processes the incoming parameter information in the function weight.
So the explanation of the shell operation of MongoDB is here first, which basically covers the most common operation method of MongoDB, then we will talk about how to drive MongoDB with Java in the next section, that is, the so-called crud.
"Recommended" MongoDB basic command Daquan