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:
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 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".
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; 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 native mydb data to the TEMP database
7. Repairing the current database
DB. RepairDatabase();
8. View the database currently in use
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
DB. Stats();
10. Current DB version
DB. Version();
11. View the current DB link machine address
DB. Getmongo();
Collection Aggregation 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();
User-related
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");
other1, the error message before the query db. Getpreverror(); 2, clear Error Record 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 ();
Clustered collection Query
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 ";"
But you can set the size of the data displayed per page, using Dbquery. shellbatchsize=; This results in 50 records per page.
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});
Select = $;
Records for > 22
DB. userInfo. Find({age: {$gt: 22}});
Equivalent:select>;
Records for < 22
DB. userInfo. Find({age: {$lt: 22}});
Equivalent:select<;
>= 25 of records
DB. userInfo. Find({age: {$gte: 25}});
Equivalent:select>=;
<= 25 of records
DB. userInfo. Find({age: {$lte: 25}});
> <= 26
DB. userInfo. Find({age: {$gte: $lte: 26}});
9. Query the data containing MONGO in name
DB. userInfo. Find({name:/mongo/});
Equal to percent
Select * from UserInfo where name is 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.
> 25
DB. userInfo. Find({age: {$gt: +}}, {name:1, age:1});
Equivalent:select>;
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:selecttop* 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. userInfoFind()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:select=;
19. Query the first piece of data
DB. UserInfo. FindOne();
Equivalent:selecttop* 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:select>=;
21. Sort by a 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. 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();
Modify, 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. Usersupdate({age:25}, {$set: {name: ' ChangeName '}}, False, True);
= 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({
Update: {$set: {name: ' A2 '}, $inc: {age:2}},
Remove:true
});
DB. RunCommand
Update: {$set: {name: ' A2 '}, $inc: {age:2}},
Remove:true
});
update or remove One of them is a required parameter; Additional 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 |
Statement block operations
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 (vari= 0; I < ; I+ +) {
.. db. Users. Saveiii % 2});
... };
This adds 30 data to the loop, and you can also omit the notation
> for (vari= 0; I < ; I+ +) db. Users. Saveiii % 2});
It is also possible to use it to view the information on the next page when you use the DB. Usersfind() query to display multiple data without a single page display.
4. Find Cursor Query
> var cursor = DB. Users. Find();
> while (cursor. Hasnext
Printjson (cursornext
}
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. Usersfind(). 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, you can get its length:cursor. Length(), or cursor. Count();
So we can also display the data in a loop
for (vari = 0, Len = C. lengthi<Len; I+ +) Printjson (c[i]);
7. Convert the Find cursor to an array
> var arr = db. Usersfind(). ToArray();
> Printjson (arr[2]);
To convert it to an array using the ToArray method
8. Customize our own query results
<= 28 and displays only the age column data
DB. UsersFind({age: {$lte: Age:1}). ForEach(Printjson);
DB. UsersFind({age: {$lte: Age:true}). ForEach(Printjson);
Exclude The Age column
DB. UsersFind({age: {$lte: Age:false}). ForEach(Printjson);
9. The Foreach transfer function displays information
DB. Things. Find({x:4}). ForEach(function (x) {print (Tojson (x));});
MongoDB Basic command with