MongoDB shell operations
Experimental principle
MongoDB shell is an executable file, an interactive JavaScript shell that comes with MongoDB, and is located in the /bin folder under the MongoDB installation path. To start the MongoDB shell, execute the command mongo. This will launch the shell in a console prompt. MongoDB shell provides multiple commands. Below are listed several MongoDB shell commands and their uses.
1. MongoDB shell script programming
1. Use command line programming –eval to execute JavaScript expressions
Parameter –eval accepts a JavaScript string or JavaScript file. The following command starts the MongoDB shell, connects to the database test, executes db.getCollectionNames() on the database, and outputs the result as a JSON string.
step:
1) Create a new collection student in the test database and add documents. The command is as follows:
MongoDB shell side operation
>use test
>db.student.insert({sno:”001”,sname:”zhangsan”})
>exit
2) Enter in the console:
> mongo test --eval “printjson(db.getCollectionNames())”
2. Use the load() method in the MongoDB shell to execute the script
1) Create the shell_script.js file. The path of the file is D:\Junior Experiment\nosql\NoSQL guide book\test1document\shell_script.js. The file code is as follows:
print("Hostname:");
print("\t"+hostname());
print("Date:");
print("\t"+Date());
db = connect("localhost/admin");
print("Admin Collections:");
printjson(db.getCollectionNames());
2) Execute the command mongo file address + shell_script.js. The command execution result is as shown in the figure.
3. Specify the JavaScript file to be executed in the command mongo
MongoDB shell loads and executes the script file generate_words.js. Assume the path to the file is
D:\JuniorExperiment\nosql\NoSQLguidebook\test1document\generate_words.js。
1) Enter load("D:\JuniorExperiment\nosql\NoSQLguidebook\test1document\generate_words.js") on the MongoDB shell (so the address is too long, so I changed the file path)
2) Enter the command show dbs, and you can see that the custom database words is generated.
3) Enter the command use words to switch to the words database.
4) Enter the command show collections to view the collection names contained in the words database. The command execution result is shown in the figure.
5) Enter the command db.word_stats.find().pretty() to view all documents in the word_stats collection. The command execution result is shown in the figure.
2. MongoDB shell operation
Experiment content
Practice creating collections, deleting collections, inserting data, updating data, deleting data, querying data, etc. in MongoDB.
Experimental steps
1. Start the MongoDB shell.
2. Switch to the admin database and use the root account
When authorizing the admin account, the connection failed Error: Authentication failed.
. Causing robomongo to be unable to connect
The solution is to manually add the admin account. After the creation is successful, db.auth('root','strongs') again returns 1
3. Check the current database status
4. Display the current MongoDB version
5. Query the names of all local databases
6. Switch to the mydb database. If the database does not exist, it will be created after inserting the first piece of data.
7. Create a collection (a collection is equivalent to a table in a relational database)
8. Query all collections under the current library
9. Query all collections under the current library (collections)
10. Insert data into the collection mycollection. (If the collection does not exist, MongDB will automatically create the collection when inserting data)
11. Use the insert method to add data. If you add a document, you can also declare the object first and then add it. For example:
12.MongoDB will automatically generate an "_id" value for each inserted object. You can also specify this value yourself when inserting, for example:
13. Query the data in the collection mycollection
MongoDB provides two update operations: update() and save()
①The update() update operation requires at least two parameters, and its syntax is: db.collection.update(criteria, objNew, upsert, multi)
criteria: update query conditions, similar to the value after where in the sql update query.
objNew: update object and some update operators (such as , ,, inc...), etc., can also be understood as the value after set in the sql update query.
upsert: If there is no update record, whether to insert objNew, true means insert, the default is false, not insert.
multi: MongoDB defaults to false, and only updates the first record found. If this parameter is true, all multiple records found based on conditions will be updated.
14. Modify the salary based on the username, and increase the salary to 600 for data with username 'zhangyu'
15. Increase the age field value of the data with username 'wangkaiyue' by 1
②The syntax of save() is: db.collection.save(x), x is the object to be updated, which can only be a single record. You can also use Save to perform the insertion operation. If there is no identical "_id" in the system, the insertion operation will be performed. If there is, the original value will be overwritten and the update operation will be performed.
16. Update the data with _id 10000001.
17. Query the mycollection collection again to verify the above update operation
18. Delete the data with username 'yuhaowen'.
19. Delete all data in the collection mycollection
The delete syntax is as follows:
db.mycollection.remove(
<query>,
{
justOne:<boolean>,
writeConcern:<document>
}
)
Parameter Description:
query: (optional) Conditions for deleted documents.
justOne : (optional) If set to true or 1, only one document will be deleted. Default false
writeConcern: (optional) The level at which the exception is thrown.
20. Rename the collection from mycollection to mcollection
21. Delete the collection mcollection
22. Delete the current database
This experimental shell operation ends!
3. MongDB query
Experiment content
1. Use find or findOne function and query documents
2.MongoDB conditional query
3.MongoDB AND and OR queries
4.MongoDB $type operator
5.MongoDB regular expressions
Experimental steps
1. Start the MongoDB shell
2. Switch to the admin database and use the root account
3. Insert experimental data
4. Count the number of data items in the collection
5. Find is used in MongoDB to perform queries. The query returns a subset of a set, and the subset ranges from 0 to the entire set.
combine. The first parameter of find determines which subsets are to be returned, and its form is also a set.
An empty document query will match the entire content of the collection. If the query document is not specified, the default is {}.
6. Query the first piece of data
Note that the O in findOne must be capitalized
7. Query all data after Article 1
8. Skip the second item and query the last two data
This command can be used for paging, Limit is pageSize, Skip is page *pageSize
9. Limit query to 3 pieces of data
10. Query the number of records in the result set. (Query the number of salaries less than 300 or greater than 400)
Query the data of the specified column. You can specify the desired key through the second parameter of find (or findOne), which will save
It saves the amount of data transmitted and saves the client’s time and memory consumption in decoding documents.
11. Query the 'age' column and 'salary' column in the mycollection collection
1 indicates the meaning of displaying this column, and can also be expressed by true
12. Sort by salary in ascending order. (Replace 1 with -1 to sort in descending order)
13. Query the username column and remove duplicate data
Comparison of Where statements in MongoDB and RDBMS:
14. Query data with age less than 13
15. Query the data whose age is equal to 13
16. Query data with age greater than 15
17. Query data not equal to 13
MongoDB AND conditions
MongoDB's find() method can pass in multiple keys, each key separated by commas. The syntax format is as follows:
db.col.find({key1:value1,key2:value2})
18. Query the data with age equal to 20 and salary equal to 200
19. Query the data whose age is less than 13 and salary is greater than or equal to 200.
MongoDB OR condition
The MongoDB OR conditional statement uses the keyword $or, and the syntax format is as follows:
db.col.find(
{
$or:[
{key1:value1},{key2:value2}
]
}
)
20. Query data with salary greater than 300 or age less than or equal to 13.
AND and OR used together
21. Query the data whose username is 'banma' or age is 8 when salary is greater than or equal to 300, similar conventional SQL statement
为:where salary>=300 and (username = ‘banma’ or age = 8)
MongoDB $type operator
The $type operator retrieves the matching data type in the collection based on the BSON type and returns the result.
The types that can be used in MongoDB are shown in the following table:
22. Get the data of username in the mycollection collection as String type.
MongoDB regular expressions
Regular expressions use a single string to describe and match a series of strings that conform to a certain syntax rule.
23. Query the data containing 'm' in username.
24. Query data starting with z