After MongoDB is started successfully, open a command line window and enter mongo to perform database operations. Enter help to see the basic operation command: showdbs: display the Database List showcollections: display the set in the current database (similar to the tables in the relational database) showusers: display the user usedbname: Switch
After MongoDB is started successfully, open a command line window and enter mongo to perform database operations. Enter help to see the basic operation command: show dbs: display the Database List show collections: display the set in the current database (similar to the tables in the relational database) show users: display the user use db name: Switch
After MongoDB is started successfully, open a command line window and enter mongo to perform database operations.
Enter help to view the basic operation commands:
Show dbs: displays the Database List
Show collections: displays a set in the current database (similar to a table in a relational database)
Show users: displays users
Use : Switch the current database, which means the same as in the MS-SQL
Db. help (): displays database operation commands, which contain many commands.
Db. foo. help (): displays the set operation commands. There are also many commands. foo refers to a set named foo in the current database, not a real command.
Db. foo. find (): searches for the foo set in the current database (all data is listed due to no conditions)
Db. foo. find ({a: 1}): searches for the foo set in the current database. The condition is that the data has an attribute named a and the value of a is 1.
MongoDB does not have commands for creating databases, but similar commands are available.
For example, if you want to create a database named "myTest", run the use myTest command first and then perform some operations (such as db. createCollection ('user') to create a database named "myTest.
Common database commands
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 you create a set (table), 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 data of mydb on 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 ();
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. userInfo. getDB () of the current collection ();
5. Get the current cluster status db. userInfo. stats ();
6. Get the total size of the clustered set db. userInfo. totalSize ();
7. Cluster set storage space size db. userInfo. storageSize ();
8. Shard version information? Db. userInfo. getShardVersion ()
9. Rename db. userInfo. renameCollection ("users") for the clustering set; rename userInfo to users
10. Delete 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: 'zhangsan', 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: selecttop 5 * from userInfo;
16. Query 10 data records later
db.userInfo.find().skip(10);
Equivalent to: select * from userInfo where id not in (
selecttop 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: selecttop 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: ‘zhangsan’, 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: 'hoho'}}, 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.
Parameter description default value query filtering condition {} sort if multiple documents meet the query filtering condition, the first object is selected in the order specified by this parameter, this object will be operated {} remove if it is true, the selected object will be deleted before the return N/A update A modifier object N/A new if it is true, the modified object instead of the original object will be returned. This parameter is ignored during the delete operation. False fields refer to Retrieving a Subset of Fields (1.5.0 +) All fields upsert to create a new object. If the query result is blank. 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 (vari= 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 (vari= 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
>varcursor = db.users.find();
> while (cursor.hasNext()) {
printjson(cursor.next());
}
In this way, all users information can be queried.
varcursor = 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
varcursor = 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 (vari = 0, len = c. length (); 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));});
Original article address: apsaradb for MongoDB is basically used. Thank you for sharing it with the original author.